Ark Server API (ASA) - Wiki
Loading...
Searching...
No Matches
MovingWindowAverageFast.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2#pragma once
3#include "CoreMinimal.h"
4#include "Containers/StaticArray.h"
5
6/**
7 * This class calculates a moving window average. Its designed to be used with floats or doubles and
8 * keeps track of the average with every value pushed so is ideal when there is a one to one or one to many relationship
9 * between calls to PushValue() and GetMovingWindowAverage() respectively.
10 */
11template <typename T, int32 ArraySize>
12class FMovingWindowAverageFast
13{
14public:
15 FMovingWindowAverageFast()
16 : TotalValues(static_cast<T>(0))
17 , AverageValue(static_cast<T>(0))
18 , RemoveNextIdx(0)
19 , NumValuesUsed(0)
20 {
21 static_assert(ArraySize > 0, "ArraySize must be greater than zero");
22 }
23
24 void PushValue(T Value)
25 {
26 T ValueRemoved = static_cast<T>(0);
27
28 const T NumItemsPrev = static_cast<T>(NumValuesUsed);
29
30 if (ArraySize == NumValuesUsed)
31 {
32 ValueRemoved = ValuesArray[RemoveNextIdx];
33 ValuesArray[RemoveNextIdx] = Value;
34 RemoveNextIdx = (RemoveNextIdx + 1) % ArraySize;
35 }
36 else
37 {
38 ValuesArray[NumValuesUsed] = Value;
39 ++NumValuesUsed;
40 }
41
42 const T MovingWindowItemsNumCur = static_cast<T>(NumValuesUsed);
43 TotalValues = TotalValues - ValueRemoved + Value;
44 AverageValue = TotalValues / MovingWindowItemsNumCur;
45 }
46
47 T GetAverage() const
48 {
49 return AverageValue;
50 }
51
52private:
53 TStaticArray<T, ArraySize> ValuesArray;
54
55 T TotalValues;
56 T AverageValue;
57
58 /** The array Index of the next item to remove when the moving window is full */
59 int32 RemoveNextIdx;
60 int32 NumValuesUsed;
61};