question
Given a stream of numbers, write an algorithm to print the average (mean) of the stream at any point.
Ex. 10, 20, 30, 40...
Average after 1 number = 10
Average after 2 numbers = 15
Average after 3 numbers = 20
Average after 4 numbers = 25
...
Ex. 10, 20, 30, 40...
Average after 1 number = 10
Average after 2 numbers = 15
Average after 3 numbers = 20
Average after 4 numbers = 25
...
Average is defined as: sum of all numbers / count of all numbers
All we need for each consective integer is the previous average (
Thoughts or alternate solution? Let us know in the comments below!
prev
) and the count (n
) of all previous numbers. The average after including new number x
is (prev*n + x)/(n + 1)
.
Thoughts or alternate solution? Let us know in the comments below!