-
Notifications
You must be signed in to change notification settings - Fork 0
/
MovingMaxTask.cs
89 lines (81 loc) · 2.84 KB
/
MovingMaxTask.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
namespace yield
{
public static class MovingMaxTask
{
private static double _localMax;
private static LinkedList<double> _dequeMaximums;
private static Queue<double> _queueWindow;
public static IEnumerable<DataPoint> MovingMax(this IEnumerable<DataPoint> data, int windowWidth)
{
var counter = 0;
_localMax = 0.0;
_dequeMaximums = new LinkedList<double>();
_queueWindow = new Queue<double>();
foreach (var dataPoint in data)
{
if (counter == 0)
{
AddFirstPointToLists(dataPoint);
}
else if (counter < windowWidth)
{
DeleteSmallerPoints(dataPoint);
AddAsFirstOrAddAsLast(dataPoint);
}
else
{
if (IsMaximumShouldGone())
{
_queueWindow.Dequeue();
_dequeMaximums.RemoveFirst();
_localMax = _dequeMaximums.Count != 0 ? _dequeMaximums.First.Value : dataPoint.OriginalY;
DeleteSmallerPoints(dataPoint);
AddAsFirstOrAddAsLast(dataPoint);
}
else
{
_queueWindow.Dequeue();
DeleteSmallerPoints(dataPoint);
AddAsFirstOrAddAsLast(dataPoint);
}
}
counter++;
yield return dataPoint.WithMaxY(_dequeMaximums.First.Value);
}
}
private static bool IsMaximumShouldGone()
{
return Math.Abs(_queueWindow.Peek() - _localMax) < 1e-7;
}
private static void AddAsFirstOrAddAsLast(DataPoint dataPoint)
{
if (_dequeMaximums.Count == 0)
AddFirstPointToLists(dataPoint);
else
AddLastPointToLists(dataPoint);
}
private static void DeleteSmallerPoints(DataPoint dataPoint)
{
while (_dequeMaximums.Count != 0)
{
if (_dequeMaximums.Last.Value < dataPoint.OriginalY)
_dequeMaximums.RemoveLast();
else
return;
}
}
private static void AddFirstPointToLists(DataPoint dataPoint)
{
_localMax = dataPoint.OriginalY;
_queueWindow.Enqueue(_localMax);
_dequeMaximums.AddFirst(_localMax);
}
private static void AddLastPointToLists(DataPoint dataPoint)
{
_dequeMaximums.AddLast(dataPoint.OriginalY);
_queueWindow.Enqueue(dataPoint.OriginalY);
}
}
}