Group Consecutive Runs In A Slice

Collapse consecutive equal values into runs of value and length with one pass over the slice, matching on the previous run to extend or start a new one.

RustData Integrity

Code

rustsnippet
21 lines
// 把连续(consecutive)相同值合并成 run:值与长度成对返回
fn group_runs<T: PartialEq>(items: &[T]) -> Vec<(&T, usize)> {
    let mut runs: Vec<(&T, usize)> = Vec::new();
    for item in items {
        match runs.last_mut() {
            // 与上一项相同:延长当前 run
            Some((value, len)) if *value == item => *len += 1,
            _ => runs.push((item, 1)),
        }
    }
    runs
}

fn main() {
    let levels = ["info", "info", "warn", "warn", "warn", "info", "error"];
    let runs = group_runs(&levels);
    for (value, len) in &runs {
        println!("{len} x {value}");
    }
    println!("run count: {}", runs.len());
}

How the snippet works

Group Consecutive Runs In A Slice reduces to the functions group_runs and main.

Repetition is confined to for item in items — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Using it

Look for the run count: prefixes when the file runs; they tie each line to its step.

There are 1 call inside main — group_runs — executed top to bottom.

Key statements

fn group_runs<T: PartialEq>(items: &[T]) -> Vec<(&T, usize)> {
let mut runs: Vec<(&T, usize)> = Vec::new();
for item in items {
match runs.last_mut() {
// 与上一项相同:延长当前 run
Some((value, len)) if *value == item => *len += 1,
_ => runs.push((item, 1)),
}
}
runs
}

Interactive Tools for This Topic

FAQ

What does Group Consecutive Runs In A Slice print when run?
Run it as a complete program — the output lines carry labels such as `run count:`.