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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With