-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathCircularBuffer.java
56 lines (47 loc) · 1.17 KB
/
CircularBuffer.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
package com.team254.lib.util;
import java.util.LinkedList;
/**
* Implements a simple circular buffer.
*/
public class CircularBuffer {
final int mWindowSize;
final LinkedList<Double> mSamples;
double mSum;
public CircularBuffer(int window_size) {
mWindowSize = window_size;
mSamples = new LinkedList<>();
mSum = 0.0;
}
public void clear() {
mSamples.clear();
mSum = 0.0;
}
public double getAverage() {
if (mSamples.isEmpty())
return 0.0;
return mSum / mSamples.size();
}
public void recomputeAverage() {
// Reset any accumulation drift.
mSum = 0.0;
if (mSamples.isEmpty())
return;
for (Double val : mSamples) {
mSum += val;
}
mSum /= mWindowSize;
}
public void addValue(double val) {
mSamples.addLast(val);
mSum += val;
if (mSamples.size() > mWindowSize) {
mSum -= mSamples.removeFirst();
}
}
public int getNumValues() {
return mSamples.size();
}
public boolean isFull() {
return mWindowSize == mSamples.size();
}
}