Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round robin array in C#

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?

like image 458
beardedeagle Avatar asked Dec 18 '22 18:12

beardedeagle


1 Answers

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));
like image 59
Dmitry Bychenko Avatar answered Jan 04 '23 12:01

Dmitry Bychenko