Problems › TypeScript › patterns
The average so far, after every reading
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.
- Every reading is zero or more.
- After each reading, report the mean of every reading so far.
- Drop the fraction — the mean is rounded down to a whole number.
- An empty run of readings gives an empty result.
runningAverage(readings: list<int>) → list<int>
Where you start
function runningAverage(readings: number[]): number[] {
}
Worked examples
| Call | Result |
|---|---|
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 TypeScript
function runningAverage(readings: number[]): number[] {
const out: number[] = [];
let total = 0;
for (let i = 0; i < readings.length; i += 1) {
total += readings[i];
out.push(Math.floor(total / (i + 1)));
}
return out;
}