I am trying to make an round robin array. If I were to feed this array a bunch of values in a loop and I hit the end of the array (let's say it is 10 in length), how would I loop around to the first index?
When looping, use modular algebra to compute array's index:
myArray[index % myArray.Length]
Sample
int[] myArray = new int[10];
// Round robin feeding; trying to put 0, 1, .. 13 into int[10]:
for (int i = 0; i < 14; ++i) // note 14 > 10
myArray[i % myArray.Length] = i; // i % myArray.Length - modular arithmetics
// Test
// 10, 11, 12, 13, 4, 5, 6, 7, 8, 9
// note that first 4 values (10, 11, 12, 13) are overriden
Console.Write(String.Join(", ", myArray));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With