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:?}");
}
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.Text StatisticsCount characters, words, lines, sentences, paragraphs, and estimated reading time entirely in the browser with no text sent to a server.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.