Last active
June 27, 2023 15:21
-
-
Save prianichnikov/e92b1a1d1e94035bf7bc26bcf3e1c617 to your computer and use it in GitHub Desktop.
Moving average implementation
This file contains hidden or 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 class MovingAverage { | |
private final int[] array; | |
private int index; | |
private long sum; | |
public MovingAverage(int size) { | |
this.array = new int[size]; | |
this.index = 0; | |
} | |
public double next(int value) { | |
if (index == array.length) { | |
index = 0; | |
} | |
sum = sum - array[index] + value; | |
array[index++] = value; | |
return (double) sum / array.length; | |
} | |
public static void main(String[] args) { | |
MovingAverage m = new MovingAverage(3); | |
System.out.println(m.next(1)); | |
System.out.println(m.next(10)); | |
System.out.println(m.next(3)); | |
System.out.println(m.next(5)); | |
System.out.println(m.next(1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment