Skip to content

Instantly share code, notes, and snippets.

@lukepuplett
Created August 7, 2019 17:31
Show Gist options
  • Save lukepuplett/728929569be94b0d7525e14418550d85 to your computer and use it in GitHub Desktop.
Save lukepuplett/728929569be94b0d7525e14418550d85 to your computer and use it in GitHub Desktop.
How to round robin writing to an array
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;
}
@lukepuplett
Copy link
Author

lukepuplett commented Aug 7, 2019

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 time r % 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.

@lukepuplett
Copy link
Author

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