Skip to content

Example: Moving Average of size values

Roberto Fronteddu edited this page Mar 17, 2024 · 1 revision
public class MovingAverage {
    int size;
    double sum;
    Queue<Integer> window;

    MovingAverage(int size) {
        this.size = size;
        sum = 0;
        window = new LinkedList<>();
    }

    double next (int val) {
        if (window.size() == size) {
            sum -= window.poll();
        }
        sum += val;
        window.add(val);
        return sum / window.size();
    }
}
Clone this wiki locally