在C中随机播放多维数组
Shuffle multidimensional array in C
我正在尝试将这个多维数组洗牌成另一个数组,就像一副纸牌一样。
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;
}
}
但我收到奇怪的错误:无效的数组分配。我认为这是因为我使用的是多维数组。有人可以帮我吗?谢谢
您需要复制各个列,如下所示:
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;
}
}
}
我正在尝试将这个多维数组洗牌成另一个数组,就像一副纸牌一样。
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;
}
}
但我收到奇怪的错误:无效的数组分配。我认为这是因为我使用的是多维数组。有人可以帮我吗?谢谢
您需要复制各个列,如下所示:
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;
}
}
}