Search code examples
javaarraylistrolling-average

How do I calculate the moving average of the 7 most recent values after the first Seven values in java?


My question is how do I calculate the moving average of the 7 most recent values using ArrayList after the first seven values?

This is my code for the first seven values, what I fail to understand is how I would get the average of the 7 most recent values after the first seven values, I would really appreciate it if anyone could help me with this.

import java.util.ArrayList;

import java.io.*;

import java.util.Scanner;

public class MovingAverage{

public static void main(String[]args) throws FileNotFoundException{
    int sum = 0;
    Scanner s = new Scanner(new File("values.txt"));

    ArrayList<Integer> values = new ArrayList<>();
    ArrayList<Integer> averages = new ArrayList<>();
    
    System.out.println("\tValue"+"\t\tRolling Average");
    System.out.println();
    while(s.hasNext())
    {
        values.add(s.nextInt());
    }
     
    for(int i = 0; i<7;i++)
    {
        sum = sum + values.get(i);
        averages.add(sum/(i+1));

        System.out.println("\t"+values.get(i)+"\t\t"+averages.get(i));
    }
   
}

}


Solution

  • Let say you have N (>=K) numbers, and want to calculate the rolling average, then below is an easy procedure:

    import java.util.*;
    class Main
    {
        public static void rollingAverage(ArrayList<Integer> list, int K)
        {
            int sum = 0;
            int avg = 0;
            int N = list.size();
            // This part calculates the average of first (i+1) values
            for (int i=0; i<K; i++)
            {
                sum += list.get(i);
                avg = sum / (i+1);
            }
            // This part calculates the rolling average (average of `K` recent values)
            for (int i=K; i<N; i++)
            {
                sum -= list.get(i-K);   // Subtracting `i-k`th value
                sum += list.get(i);     // Adding current number
                avg = sum / K;
                System.out.println( avg );
            }
        }
        public static void main (String [] arg)
        {
            ArrayList<Integer> list = new ArrayList<>
            (Arrays.asList(10,10,10,10,10,10,10,80,150,220));
            rollingAverage( list , 7 ); // O/P : 20 40 70
        }
    }
    

    You can implement your rolling average program using the above approach easily. Feel free to ask any doubt.