Created
August 7, 2019 17:31
-
-
Save lukepuplett/728929569be94b0d7525e14418550d85 to your computer and use it in GitHub Desktop.
How to round robin writing to an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int length = 10; | |
var numbers = new int[length]; | |
int r = 0; | |
for (int i = 0; i < 100000; i++) | |
{ | |
r = unchecked(r + 1); | |
numbers[r % length] = r; | |
} |
I think .NET integers are unchecked by default so this might work, too.
numbers[r++ % length] = value;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This could be useful for computing rolling averages, for example. If the something like a flow-rate is written into the array (instead of the sample value
r
above) then periodically, every timer % length == 9
perhaps, the code could tot-up the average.Storing 1.0 or 0.0 floats for successes and failures could be used to take an average and compute a reliability for a circuit-breaker.