TryBugHunt
rustOff-by-oneHard

Moving average drops the last window

BugFind the bug and fix the code

What it should do

moving_average(values, window) returns the average of every group of window values in a row, for a chart of daily sales. The list always has at least window values. Example: moving_average(&[1.0, 2.0, 3.0, 4.0], 2) → [1.5, 2.5, 3.5]

What happens instead

moving_average(&[1.0, 2.0, 3.0, 4.0], 2) returns [1.5, 2.5] instead of [1.5, 2.5, 3.5], and moving_average(&[2.0, 4.0, 6.0], 3) returns [].

fn moving_average(values: &[f64], window: usize) -> Vec<f64> {
    let mut result = Vec::new();
    for i in 0..values.len() - window {
        let sum: f64 = values[i..i + window].iter().sum();
        result.push(sum / window as f64);
    }
    result
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the off-by-one errors pattern

The loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

What you'll practise

A hard Rust debugging exercise about off-by-one errors: the loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: A window starting at i covers values[i..i + window], so the last window starts at len - window. That start must be included. The range 0..len - window stops one before it, so the final window is never averaged, and when the list is exactly one window long nothing is returned.

The fix: Make the range inclusive: 0..=values.len() - window. A list of n values has n - window + 1 windows.

Remember: count the windows by hand for a tiny case. If the count should be n - k + 1, the loop needs ..= at the end. Rust's windows(k) method does this for you.

The pattern behind it: off-by-one errors.

More off-by-one errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/58cc23f2-0f75-4da1-8c8d-b5b7cbc12515" title="Debugging challenge: Moving average drops the last window" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/58cc23f2-0f75-4da1-8c8d-b5b7cbc12515">TryBugHunt</a></p>