C 在2个数组中重复

C 在2个数组中重复,c,C,所以我要做的是在两个数组x_cord和y_cord中填充最大数量的值。在这种情况下,两个数组最多可容纳5个唯一元素,每个元素必须介于0和2之间。之后,一旦数组完全随机化,我就会将值写入一个文件中 它看起来像这样: 0 0 1 2 2 1 2 2 0 1 我不希望任何一行都不是另一行的副本,但是我遇到了麻烦,我正在创建另一行的副本,任何帮助都将不胜感激 代码: (j=0;j

所以我要做的是在两个数组x_cord和y_cord中填充最大数量的值。在这种情况下,两个数组最多可容纳5个唯一元素,每个元素必须介于0和2之间。之后,一旦数组完全随机化,我就会将值写入一个文件中

它看起来像这样:

 0 0 
 1 2 
 2 1
 2 2 
 0 1
我不希望任何一行都不是另一行的副本,但是我遇到了麻烦,我正在创建另一行的副本,任何帮助都将不胜感激

代码:

(j=0;j{ (x_线[j]=rand()%max_x+1); (y_线[j]=rand()%max_y); 对于(m=j+1;m不要重复生成一对,直到找到唯一的一对,而是生成所有对,然后洗牌这些对

int max_y = 2;
int max_x = 2;
size_t num_eles = (max_x+1)*(max_y+1);
size_t desired_num_eles = 6;

if (desired_num_eles > num_eles)
   desired_num_eles = num_eles;

int* y_cord = malloc(sizeof(int) * num_eles);
int* x_cord = malloc(sizeof(int) * num_eles);

for (int y = max_y; y--; ) {
   for (int x = max_x; x--; ) {
      size_t i = y * max_x + x;
      y_cord[i] = y;
      x_cord[i] = x;
   }
}

for (size_t i = 0; i<desired_num_eles; ++i) {
    size_t j = rand() % (num_eles - i) + i;
    // Swap i and j
    y_cord[i] ^= y_cord[j];  y_cord[j] ^= y_cord[i];  y_cord[i] ^= y_cord[j];
    x_cord[i] ^= x_cord[j];  x_cord[j] ^= x_cord[i];  x_cord[i] ^= x_cord[j];
}

num_eles = desired_num_eles;
y_cord = realloc(sizeof(int) * num_eles);
x_cord = realloc(sizeof(int) * num_eles);
int max_y=2;
int max_x=2;
大小(最大x+1)*(最大y+1);
所需大小\u数量\u eles=6;
如果(所需数量>数量)
所需数量=数量;
int*y_cord=malloc(sizeof(int)*num_eles);
int*x_cord=malloc(sizeof(int)*num_eles);
对于(int y=max_y;y--){
对于(int x=max_x;x--){
尺寸i=y*max\ux+x;
y_线[i]=y;
x_线[i]=x;
}
}

对于(size_t i=0;代码中的等距空格将被欣赏到将初始值赋值移出m上的循环。同时将该循环限制为仅转到迄今为止生成的值对的数量。与其生成元素并检查它们是否唯一,不如生成所有元素,然后将元素无序移动。将m=j+1,然后移动g在初始for循环中生成的值?您真的不需要像
(y\u cord[j]=rand()%max\u y);
这样的赋值周围加上括号-使用正统的
y\u cord[j]=rand()%max\u y;
而不加括号(并在
%
操作符周围加上额外的空格)会非常、非常、非常、非常明智。你甚至没有始终如一地这样做-你有一个
(x_cord[j]=rand()%max_x+1)
的实例和一个
x_cord[j]=rand()%max_x+1;
的实例。在编程中,始终如一非常重要;现在就学会保持一致。
int max_y = 2;
int max_x = 2;
size_t num_eles = (max_x+1)*(max_y+1);
size_t desired_num_eles = 6;

if (desired_num_eles > num_eles)
   desired_num_eles = num_eles;

int* y_cord = malloc(sizeof(int) * num_eles);
int* x_cord = malloc(sizeof(int) * num_eles);

for (int y = max_y; y--; ) {
   for (int x = max_x; x--; ) {
      size_t i = y * max_x + x;
      y_cord[i] = y;
      x_cord[i] = x;
   }
}

for (size_t i = 0; i<desired_num_eles; ++i) {
    size_t j = rand() % (num_eles - i) + i;
    // Swap i and j
    y_cord[i] ^= y_cord[j];  y_cord[j] ^= y_cord[i];  y_cord[i] ^= y_cord[j];
    x_cord[i] ^= x_cord[j];  x_cord[j] ^= x_cord[i];  x_cord[i] ^= x_cord[j];
}

num_eles = desired_num_eles;
y_cord = realloc(sizeof(int) * num_eles);
x_cord = realloc(sizeof(int) * num_eles);