在C中随机多维数组

时间:2015-12-10 13:22:49

标签: c multidimensional-array shuffle

我正在尝试将这个多维数组洗牌到另一个数组中,就像一副纸牌。

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}
};

我尝试过:

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

但是我得到了奇怪的错误:无效的数组赋值。我想这是因为我正在使用多维数组。有人可以帮帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

您需要复制各个列,如下所示:

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;
     }
  }
}