Sliding Window Statistics with Iterators

Compute rolling sums and averages over fixed-size windows with slice iterators, avoiding index loops and extra allocations.

RustData Integrity

Code

rustsnippet
28 lines
fn rolling_average(values: &[f64], window: usize) -> Vec<f64> {
    if window == 0 || window > values.len() {
        return Vec::new();
    }
    values
        .windows(window)
        .map(|chunk| chunk.iter().sum::<f64>() / window as f64)
        .collect()
}

fn rolling_max(values: &[i64], window: usize) -> Vec<i64> {
    if window == 0 || window > values.len() {
        return Vec::new();
    }
    values
        .windows(window)
        .map(|chunk| chunk.iter().copied().max().unwrap_or_default())
        .collect()
}

fn main() {
    let samples = [3.0, 5.0, 7.0, 9.0, 11.0];
    let averages = rolling_average(&samples, 3);
    let maxima = rolling_max(&[4, 1, 7, 3, 9, 2], 2);
    println!("averages: {averages:?}");
    println!("maxima: {maxima:?}");
}

What the code does

Sliding Window Statistics with Iterators is built around the functions rolling_average, rolling_max and main.

Applying it

Entry signature: fn rolling_average(values: &[f64], window: usize) -> Vec<f64>

The demo output is labeled (averages:, maxima:), so every printed line maps back to its originating operation.

main is the driver: it invokes rolling_average and rolling_max before returning.

Statements that matter

.map(|chunk| chunk.iter().copied().max().unwrap_or_default())
.collect()
}
.map(|chunk| chunk.iter().sum::<f64>() / window as f64)
.collect()
}
return Vec::new();

Interactive Tools for This Topic

FAQ

What does Sliding Window Statistics with Iterators print when run?
Running the file directly is enough — expect labeled output lines such as `averages:`, `maxima:`.