private static class RunningAvg {
private final long[] slots;
private int offset;
private long sum;
public RunningAvg(int slotCount) {
this.slots = new long[slotCount];
this.offset = 0;
}
public void add(long value) {
// add new value and remove old value (last in array) from sum
sum = value - slots[(offset+1) % slots.length];
slots[offset++ % slots.length] = value;
}
public long avg() {
int sampleCount = Math.min(this.offset, this.slots.length);
return sum / sampleCount;
}
}