-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMovingAverage.java
More file actions
38 lines (34 loc) · 1.1 KB
/
MovingAverage.java
File metadata and controls
38 lines (34 loc) · 1.1 KB
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
import java.util.LinkedList;
import java.util.Queue;
public class MovingAverage {
private final Queue<Double> window = new LinkedList<Double>();
private final int period;
private double sum;
public MovingAverage(int period) {
assert period > 0 : "Period must be a positive integer";
this.period = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > period) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.isEmpty()) return 0; // technically the average is undefined
return sum / window.size();
}
public static void main(String[] args) {
double[] testData = {1,2,3,4,5,5,4,3,2,1};
int[] windowSizes = {3,5};
for (int windSize : windowSizes) {
MovingAverage ma = new MovingAverage(windSize);
for (double x : testData) {
ma.newNum(x);
System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());
}
System.out.println();
}
}
}