Skip to content

Instantly share code, notes, and snippets.

@Jezza
Created August 30, 2019 13:53
Show Gist options
  • Save Jezza/3469ba303e0faeb83a51f86beab57305 to your computer and use it in GitHub Desktop.
Save Jezza/3469ba303e0faeb83a51f86beab57305 to your computer and use it in GitHub Desktop.
public final class RunningAverage {
private final int[] values;
private float average;
private int index;
public RunningAverage(int capacity) {
values = new int[capacity];
average = 0;
index = 0;
}
public float add(int newValue) {
int[] values = this.values;
float length = values.length;
float average = this.average;
int index = this.index;
float newAverage = (((average * length) - values[index]) + newValue) / length;
values[index] = newValue;
if (++index >= length) {
index = 0;
}
this.average = newAverage;
this.index = index;
return newAverage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment