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>
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::vector<int> runningAverage(std::vector<int> readings) {
}
Worked examples
| Call | Result |
|---|---|
runningAverage(std::vector<int>{10, 20, 30}) | std::vector<int>{10, 15, 20} |
runningAverage(std::vector<int>{1, 2}) | std::vector<int>{1, 1} |
runningAverage(std::vector<int>{5}) | std::vector<int>{5} |
runningAverage(std::vector<int>{}) | std::vector<int>{} |
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 C++
std::vector<int> runningAverage(std::vector<int> readings) {
std::vector<int> out;
int total = 0;
for (size_t i = 0; i < readings.size(); i++) {
total += readings[i];
out.push_back(total / static_cast<int>(i + 1));
}
return out;
}