forked from facchinm/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularBuffer.java
More file actions
78 lines (60 loc) · 1.42 KB
/
Copy pathCircularBuffer.java
File metadata and controls
78 lines (60 loc) · 1.42 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package processing.app.helpers;
import java.util.NoSuchElementException;
public class CircularBuffer {
private final double[] elements;
private int start = -1;
private int end = -1;
private final int capacity;
public void add(double num) {
end = (end + 1) % capacity;
elements[end] = num;
if (start == end || start == -1) {
start = (start + 1) % capacity;
}
}
public double get(int index) {
if (index >= capacity) {
throw new IndexOutOfBoundsException();
}
if (index >= size()) {
throw new IndexOutOfBoundsException();
}
return elements[(start + index) % capacity];
}
public boolean isEmpty() {
return start == -1 && end == -1;
}
public CircularBuffer(int capacity) {
this.capacity = capacity;
elements = new double[capacity];
}
public double min() {
if (size() == 0) {
throw new NoSuchElementException();
}
double out = get(0);
for (int i = 1; i < size(); ++i) {
out = Math.min(out, get(i));
}
return out;
}
public double max() {
if (size() == 0) {
throw new NoSuchElementException();
}
double out = get(0);
for (int i = 1; i < size(); ++i) {
out = Math.max(out, get(i));
}
return out;
}
public int size() {
if (end == -1) {
return 0;
}
return (end - start + capacity) % capacity + 1;
}
public int capacity() {
return capacity;
}
}