Advertisement
KoMeDiAnT

Moving average

Feb 25th, 2017
1,308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using NUnit.Framework.Constraints;
  4.  
  5. namespace yield
  6. {
  7.     public static class MovingAverageTask
  8.     {
  9.         public class QueueItem<T>
  10.         {
  11.             public T Value { get; set; }
  12.             public QueueItem<T> Next { get; set; }
  13.         }
  14.  
  15.         public class Queue<T>
  16.         {
  17.             QueueItem<T> head;
  18.             QueueItem<T> tail;
  19.  
  20.             public void Enqueue(T value)
  21.             {
  22.                 if (head == null)
  23.                     tail = head = new QueueItem<T> { Value = value, Next = null };
  24.                 else
  25.                 {
  26.                     var item = new QueueItem<T> { Value = value, Next = null };
  27.                     tail.Next = item;
  28.                     tail = item;
  29.                 }
  30.             }
  31.  
  32.             public T Dequeue()
  33.             {
  34.                 if (head == null) throw new InvalidOperationException();
  35.                 var result = head.Value;
  36.                 head = head.Next;
  37.                 if (head == null)
  38.                     tail = null;
  39.                 return result;
  40.             }
  41.         }
  42.  
  43.         public static IEnumerable<DataPoint> MovingAverage(this IEnumerable<DataPoint> data, int windowWidth)
  44.         {
  45.             int currentValue = 1;
  46.             double sum = 0.0;
  47.             var queue = new Queue<double>();
  48.  
  49.             foreach (var point in data)
  50.             {
  51.                 if (currentValue > windowWidth)
  52.                 {
  53.                     sum += point.OriginalY - queue.Dequeue();
  54.                     point.AvgSmoothedY = sum / windowWidth;
  55.                    
  56.                 }
  57.                 else
  58.                 {
  59.                     sum += point.OriginalY;
  60.                     point.AvgSmoothedY = sum / currentValue;
  61.                 }
  62.                 yield return point;
  63.                 queue.Enqueue(point.OriginalY);
  64.                 currentValue++;
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement