Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using NUnit.Framework.Constraints;
- namespace yield
- {
- public static class MovingAverageTask
- {
- public class QueueItem<T>
- {
- public T Value { get; set; }
- public QueueItem<T> Next { get; set; }
- }
- public class Queue<T>
- {
- QueueItem<T> head;
- QueueItem<T> tail;
- public void Enqueue(T value)
- {
- if (head == null)
- tail = head = new QueueItem<T> { Value = value, Next = null };
- else
- {
- var item = new QueueItem<T> { Value = value, Next = null };
- tail.Next = item;
- tail = item;
- }
- }
- public T Dequeue()
- {
- if (head == null) throw new InvalidOperationException();
- var result = head.Value;
- head = head.Next;
- if (head == null)
- tail = null;
- return result;
- }
- }
- public static IEnumerable<DataPoint> MovingAverage(this IEnumerable<DataPoint> data, int windowWidth)
- {
- int currentValue = 1;
- double sum = 0.0;
- var queue = new Queue<double>();
- foreach (var point in data)
- {
- if (currentValue > windowWidth)
- {
- sum += point.OriginalY - queue.Dequeue();
- point.AvgSmoothedY = sum / windowWidth;
- }
- else
- {
- sum += point.OriginalY;
- point.AvgSmoothedY = sum / currentValue;
- }
- yield return point;
- queue.Enqueue(point.OriginalY);
- currentValue++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement