Sliding Window Statistics with Iterators
Compute rolling sums and averages over fixed-size windows with slice iterators, avoiding index loops and extra allocations.
Code
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:?}");
}
Report a problem with this exampleOpens a pre-filled issue on GitHub.