Created
August 30, 2019 13:53
-
-
Save Jezza/3469ba303e0faeb83a51f86beab57305 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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