Tuesday, May 6, 2014

Find average of a stream of the numbers

Problem

Given a stream of numbers, print average (or mean) of the stream at every point.

Example

For example, let us consider the stream as 10, 20, 30, 40, 50, 60, …
  Average of 1 numbers is 10.00
  Average of 2 numbers is 15.00
  Average of 3 numbers is 20.00
  Average of 4 numbers is 25.00
  Average of 5 numbers is 30.00
  Average of 6 numbers is 35.00
  ..................

Solution

To print mean of a stream, we need to find out how to find average when a new number is being added to the stream. To do this, all we need is count of numbers seen so far in the stream, previous average and new number. Let n be the count, prev_avg be the previous average and x be the new number being added. The average after including x number can be written as (prev_avg*n + x)/(n+1).

float getAvg(float prev_avg, int x, int n)
{
    return (prev_avg*n + x)/(n+1);
}
 
// Prints average of a stream of numbers
void streamAvg(float arr[], int n)
{
   float avg = 0;
   for(int i = 0; i < n; i++)
   {
       avg  = getAvg(avg, arr[i], i);
       out.println("Average of "+String.valueOf(i+1)+" numbers is "+avg);
   }
   return;
}

References

Reactions:

0 comments:

Post a Comment