-
Notifications
You must be signed in to change notification settings - Fork 0
/
MovingAverageTask.cs
38 lines (36 loc) · 1.35 KB
/
MovingAverageTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Collections.Generic;
namespace yield
{
public static class MovingAverageTask
{
public static IEnumerable<DataPoint> MovingAverage(this IEnumerable<DataPoint> data, int windowWidth)
{
var isFirst = true;
var queue = new Queue<double>();
var sumWindowElements = 0.0;
foreach (var dataPoint in data)
{
if (isFirst || windowWidth == 1)
{
isFirst = false;
queue.Enqueue(dataPoint.OriginalY);
sumWindowElements += dataPoint.OriginalY;
yield return dataPoint.WithAvgSmoothedY(dataPoint.OriginalY);
}
else if (queue.Count < windowWidth)
{
sumWindowElements += dataPoint.OriginalY;
queue.Enqueue(dataPoint.OriginalY);
yield return dataPoint.WithAvgSmoothedY(sumWindowElements / queue.Count);
}
else
{
sumWindowElements -= queue.Dequeue();
sumWindowElements += dataPoint.OriginalY;
queue.Enqueue(dataPoint.OriginalY);
yield return dataPoint.WithAvgSmoothedY(sumWindowElements / windowWidth);
}
}
}
}
}