Compute A Sliding Window Over VecDeque

Maintain a bounded sliding average by popping from the front and pushing to the back of VecDeque, then cycle elements with rotate_left.

RustData Integrity

Code

snippet
use std::collections::VecDeque;

fn main() {
    const CAP: usize = 3;
    let mut window: VecDeque<f64> = VecDeque::with_capacity(CAP);
    let samples = [10.0, 20.0, 30.0, 60.0, 90.0];

    for sample in samples {
        if window.len() == CAP {
            window.pop_front();
        }
        window.push_back(sample);
        let avg = window.iter().sum::<f64>() / window.len() as f64;
        println!("window={window:?} avg={avg:.1}");
    }

    // Rotate slots in place without shifting memory manually
    window.rotate_left(1);
    println!("after rotate_left(1): {window:?}");
    window.rotate_right(1);
    println!("after rotate_right(1): {window:?}");
}

Implementation flow — Compute A Sliding Window Over VecDeque

Compute A Sliding Window Over VecDeque comes down to the function main.

The cycling part of this snippet is for sample in samples.

Watch out for

  • Touches solely native language constructs so zero remote dependencies are pulled.

Applying it

Signature: fn main()

Expect labeled output — window=, after rotate_left(1):, after rotate_right(1): — when the file runs.

Statements that matter

let avg = window.iter().sum::<f64>() / window.len() as f64;

Interactive Tools for This Topic

FAQ

What does Compute A Sliding Window Over VecDeque print when run?
Running the file directly is enough — expect labeled output lines such as `window=`, `after rotate_left(1):`, `after rotate_right(1):`.