c - 2 个数组内重复

标签 c

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

它看起来像这样:

 0 0 
 1 2 
 2 1
 2 2 
 0 1

我不希望任何行与另一行重复,但是我在创建彼此重复时遇到了麻烦,任何帮助将不胜感激。

代码:

 for (j=0; j < num_pt; j++){
        (x_cord[j] = rand()%max_x+1);
        (y_cord[j] = rand()%max_y);
         for(m=j+1; m < num_pt; m++){
             if ((x_cord[j]==x_cord[m]) && (y_cord[j]==y_cord[m])){
                    x_cord[j] = rand()%max_x+1;
             }
          }
      }
      for (j=0; j < num_pt;j++){
         fprintf(fp, "%d\t%d\n", x_cord[j], y_cord[j]);
      }

最佳答案

不要重复生成一对直到找到唯一的对,而是生成所有对,然后对这些对进行洗牌。

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

关于c - 2 个数组内重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46637944/

相关文章:

c - 这两个定义有什么区别?

Callgrind Anotate 在 OS X 10.10 中不工作

c - 如何避免单元测试中的浮点舍入错误?

c - (Linux) 从 PID 为 :VID 的附加 USB 设备获取/dev/input/eventX

c - Eclipse C/C++ 无法运行程序

c - 如何读取字符串直到两个连续的空格?

c - 从 YUV420P 到 RGB 的 FFMPEG Api 转换产生奇怪的输出

c - C 中的单链表创建

c - 多项式回归c代码

c++ - 使用套接字发送 Iplimage