Drill

ProblemsJavaScript › patterns

The average so far, after every reading

easypatternsPrefix sumsArraysMathJavaScript

A quality chart plots not each reading but the average of everything measured up to that point, so a late wobble does not swing the line.

runningAverage(readings: list<int>) → list<int>

Solve it in the editor →

Where you start

function runningAverage(readings) {
  
}

Worked examples

CallResult
runningAverage([10,20,30])[10,15,20]
runningAverage([1,2])[1,1]
runningAverage([5])[5]
runningAverage([])[]

Hint

Carry the running total and divide by how many readings you have seen. Do not re-add the list each step.

Reference solution in JavaScript
function runningAverage(readings) {
  const out = [];
  let total = 0;
  for (let i = 0; i < readings.length; i += 1) {
    total += readings[i];
    out.push(Math.floor(total / (i + 1)));
  }
  return out;
}

The same problem in another language

More patterns problems in JavaScript