forked from swastijha/SDEChallenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleMovingAverageImpl.java
57 lines (48 loc) · 1.44 KB
/
SimpleMovingAverageImpl.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
public class SimpleMovingAverageImpl implements SimpleMovingAverage<Double> {
private Queue<Double> slidingStructure;
private double incrementalSum = 0.0;
private int period;
/**
* FIFO with window implementation and we will store the sum and increment/decrement as we add values
* @param period
*/
public SimpleMovingAverageImpl(int period) {
if(period <= 0){
throw new IllegalArgumentException("Invalid window size for structure");
}
slidingStructure = new LinkedList<>();
this.period = period;
}
/**
* Add new element to the end of an queue (FIFO) and shift window to right and increment/decrement sum
*
* @param element value to be appended to queue
*/
@Override
public void add(Double element) {
if (slidingStructure.size() == period) {
incrementalSum = incrementalSum - slidingStructure.poll();
}
slidingStructure.add(element);
incrementalSum = incrementalSum + element;
}
/**
* Calculates moving average value over a given period
*
* @return moving average
*/
@Override
public Double getMovingAverage() {
return (incrementalSum / period);
}
/**
* Return number of elements in the queue
*
* @return integer of data structure size
*/
@Override
public int size() {
return slidingStructure.size();
}
}