Search code examples
c#arraysround-robin

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?


Solution

  • 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));