Search code examples
cmultidimensional-arrayshuffle

Shuffle multidimensional array in C


I'm trying to shuffle this multidimensional array into another array like a deck of cards.

int ledMatrix[25][3] = {
  {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15},
  {17,18,19}, {20,21,22}, {23,24,25}, {26,27,28}, {29,30,31},
  {33,34,35}, {36,37,38}, {39,40,41}, {42,43,44}, {45,46,47},
  {49,50,51}, {52,53,54}, {55,56,57}, {58,59,60}, {61,62,63},
  {65,66,67}, {68,69,70}, {71,72,73}, {74,75,76}, {77,78,79}
};

I tried with:

int shuffle(){
  for (int i=0; i<25; i++)
  {
     int r = random(i,25
     temp =  ledMatrix[i];
     ledMatrix[i] =  ledMatrix[r];
     ledMatrix[r] = temp;
  }
}

But i'm getting weird errors: invalid array assignment. I think this is because i'm using multidimensional arrays. Can somebody help me please? thanks


Solution

  • You need to copy the individual columns, like this:

    int shuffle(){
      for (int i=0; i<25; i++)
      {
         int r = random(i,25);
         for (int j = 0; j < 3; j++)
         {
             int temp =  ledMatrix[i][j];
             ledMatrix[i][j] =  ledMatrix[r][j];
             ledMatrix[r][j] = temp;
         }
      }
    }