Finding the average of a continuous stream of numbers
Find the average or mean of a continuously incoming stream of numbers at every point in time.
Example 1:
Input:
n = 5
arr[] = {10, 20, 30, 40, 50}
Output: 10.00 15.00 20.00 25.00 30.00
Explanation:
10 / 1 = 10.00
(10 + 20) / 2 = 15.00
(10 + 20 + 30) / 3 = 20.00
And so on.
Example 2:
Input:
n = 3
arr[] = {6, 7, 2}
Output: 6.00 6.50 5.00
Explanation:
6 / 1 = 6.00
(6 + 7) / 2 = 6.50
(6 + 7 + 2) / 3 = 5.00
method 1:
Initializes an array arr2 of size n to store the calculated averages. Initializes a variable sum to 0 to keep track of the running sum of the input numbers.
loop through the input array arr from index 0 to n-1. In each iteration, the current input number arr[i] is added to the running sum. The average of all the numbers up to the current index i is then calculated by dividing the sum by i+1 and stored in the corresponding index of the output array arr2[i].
Finally, the function returns the output array arr2 containing the calculated averages.
Java implementation:
class codemummy {float[] streamAvg(int[] arr, int n) {float[] arr2=new float[n];float sum=0;for(int i=0;i<n;i++){sum=sum+arr[i];arr2[i]=sum/(i+1);}return arr2;}}
Time Complexity: O(n)
Auxiliary Space: O(1).
c++ implementation:
#include <vector> using namespace std; vector<float> streamAvg(int arr[], int n) { vector<float> arr2(n); float sum = 0.0; for (int i = 0; i < n; i++) { sum = sum + arr[i]; arr2[i] = sum / (i + 1); } return arr2; }
Time Complexity: O(n)
Auxiliary Space: O(1).
python implementation:
def streamAvg(arr, n):arr2 = [0] * nsum = 0for i in range(n):sum += arr[i]arr2[i] = sum / (i + 1)return arr2
Time Complexity: O(n)
Auxiliary Space: O(1).
No comments