Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the rolling average of a C# array list?

I'm trying to calculate the rolling averages of every four values in an array list and add those values to a separate array list. My original array list is called numlist and it contains values from 1 to 9

List<int> numlist = new List<int>();

numlist.Add(1);
numlist.Add(2);
numlist.Add(3);
numlist.Add(4);
numlist.Add(5);
numlist.Add(6);
numlist.Add(7);
numlist.Add(8);
numlist.Add(9);

When it calculates rolling averages, it should do it in an way like this:

first average = (1+2+3+4)/4

second average = (2+3+4+5)/4

third average = (3+4+5+6)/4

and so on

so the second array list,

List<double> avelist = new List<double>();

should contain these values

{2.5, 3.5, 4.5, 5.5, 6.5, 7.5}

How can I achieve this?

like image 808
coder Avatar asked Dec 25 '22 06:12

coder


1 Answers

If you care about performance, you can use a Queue and process each item in the source only once:

IEnumerable<double> RollingAverages(IEnumerable<int> numbers, int length) {
    var queue = new Queue<int>(length);
    double sum = 0;
    foreach (int i in numbers) {
        if (queue.Count == length) {
            yield return sum / length;
            sum -= queue.Dequeue();
        }
        sum += i;
        queue.Enqueue(i);
    }
    yield return sum / length;
}

Call:

foreach (double a in RollingAverages(new List<int> {1,2,3,4,5,6,7,8,9}, 4)) {
    Console.WriteLine(a);
}
like image 170
Dennis_E Avatar answered Dec 26 '22 20:12

Dennis_E