C语言中的数组

c3frrgcw  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(121)

我试着把这个多维数组,像一副扑克牌一样, 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;
  }
}


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

roejwanj

roejwanj1#

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

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

字符串

wswtfjt7

wswtfjt72#

虽然sifferman's answer非常合理,但您也可以使用memcpy来实现值的交换。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>

int myrandom(int x, int y) {
    int result = ((double)rand() / RAND_MAX) * (y - x) + x;
    return result;
}

int main(void) {
    srand(time(NULL));

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

    for (int i = 0; i < 25; i++) {
        int r = myrandom(i, 25);
        int temp[3];
        size_t sz = sizeof(temp);
       
        memcpy(temp, ledMatrix[i], sz);
        memcpy(ledMatrix[i], ledMatrix[r], sz);
        memcpy(ledMatrix[r], temp, sz);
    }

    for (int i = 0; i < 25; i++) {
        printf("%2d, %2d, %2d\n", 
               ledMatrix[i][0], 
               ledMatrix[i][1], 
               ledMatrix[i][2]);
    }
}

字符串
输出量:

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

相关问题