Drill

ProblemsGo › patterns

The average so far, after every reading

easypatternsPrefix sumsArraysMathGo

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>

Go 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.

Solve it in Python →

Where you start

func runningAverage(readings []int) []int {
	
}

Worked examples

CallResult
runningAverage([]int{10, 20, 30})[]int{10, 15, 20}
runningAverage([]int{1, 2})[]int{1, 1}
runningAverage([]int{5})[]int{5}
runningAverage([]int{})[]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 Go
func runningAverage(readings []int) []int {
	out := []int{}
	total := 0
	for i, reading := range readings {
	    total += reading
	    out = append(out, total/(i+1))
	}
	return out
}

The same problem in another language

More patterns problems in Go