-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamAverage.java
More file actions
42 lines (38 loc) · 1010 Bytes
/
StreamAverage.java
File metadata and controls
42 lines (38 loc) · 1010 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package array;
/**
* Consider a stream of doubles. At any moment find the moving average of the
* last k numbers. If received less than k numbers than return average of only
* those numbers.
*
* Link: http://www.geeksforgeeks.org/average-of-a-stream-of-numbers/
*
* @author shivam.maharshi
*/
public class StreamAverage {
public static void runningAverage(double[] stream, int k) {
double avg = 0F;
double[] store = new double[k];
int i = 0, sl = stream.length;
boolean touchedK = false;
for (int j = 0; j < sl; j++) {
if (j == k) {
touchedK = true;
}
if (i == k) {
i = 0;
}
if (touchedK) {
avg = (avg * k - store[i] + stream[j]) / k;
} else {
avg = (avg * (j) + stream[j]) / (j + 1);
}
System.out.println(avg);
store[i] = stream[j];
i++;
}
}
public static void main(String[] args) {
double[] stream = new double[] { 1, 3, 5, 7, 0, 2, 5, 6 };
StreamAverage.runningAverage(stream, 3);
}
}