Running Average
Receives an array of integers and a window size w. It computes the average of every consecutive block of w elements: instead of re-adding each window from scratch, it keeps a running sum and slides the window one position at a time — adding the value that enters on the right and subtracting the one that leaves on the left — so the whole pass costs O(n). Each average is rounded to two decimals. Returns an array with one average per window, in order; if w is larger than the array (or not positive) it returns an empty array, and when w equals the array length it returns a single average.
Visualization
- Input
- Result
Algorithm code
// Running Average — a single pure function. Receives an array of integers and a
// window size w, and returns the average of every consecutive window of size w,
// rounded to 2 decimals. It keeps a running sum and slides the window one step
// at a time (add the entering value, subtract the leaving one), so it runs in O(n).
/**
* @param {number[]} arr - array of integers
* @param {number} w - window size (elements per window)
* @returns {number[]} average of every length-w window, rounded to 2 decimals
*/
export function runningAverage(arr, w) {
const averages = [];
if (w <= 0 || w > arr.length) {
return averages;
}
let sum = 0;
for (let i = 0; i < w; i += 1) {
sum += arr[i];
}
averages.push(round2(sum / w));
for (let i = w; i < arr.length; i += 1) {
sum += arr[i] - arr[i - w];
averages.push(round2(sum / w));
}
return averages;
}
/** Rounds a number to two decimals. */
function round2(value) {
return Math.round(value * 100) / 100;
} FUNCTION runningAverage(arr, w):
averages ← empty list
IF w ≤ 0 OR w > length(arr):
RETURN averages
sum ← 0
FOR i FROM 0 TO w - 1:
sum ← sum + arr[i]
append round2(sum / w) to averages
FOR i FROM w TO length(arr) - 1:
sum ← sum + arr[i] - arr[i - w]
append round2(sum / w) to averages
RETURN averages
FUNCTION round2(value):
RETURN round(value * 100) / 100