【问题标题】:Generate 8 different Coordination生成 8 种不同的坐标
【发布时间】:2021-03-20 14:11:49
【问题描述】:

我正在尝试编写一个获取数组的函数,生成 8 个不同的坐标。 我有一些大小为 8 的结构数组,它将一些坐标保存在另一个数组([8][8])中。 我正在尝试获取八个不同的坐标,但不幸的是,有时我会得到相同的坐标。

代码如下:

struct location {
int x;
int y;
};
void setCoordinations(struct locaction loc[]) /// the array is empty.
{
    int i = 0, j = 8; 
    srand(time(NULL));


    array[i].x = rand() % 8;
    array[i].y = rand() % 8;
    for (int i = 1; i <8; i++)
    {
        
        array[i].x = (rand() +i) % 8;
        array[i].y= (rand() -j)  % 8;
    }

我知道我可以使用 Fisher-Yates shuffle,但我的主要问题是,例如,我可以拥有一次坐标 (6,6),但不能拥有两次。 我需要 8 个随机的唯一坐标。

我将如何实现这个?

【问题讨论】:

标签: c random srand


【解决方案1】:

如果此处的算法(唯一坐标)有问题,请检查您新创建的坐标与数组中已创建的坐标。

void setCoordinations(struct locaction loc[]) /// the array is empty.
{
    int i, j = 8, k; 
    srand(time(NULL));

    loc[0].x = rand() % 8;
    loc[0].y = rand() % 8;
    for (i = 1; i < 8; )
    {
        loc[i].x = (rand() + i) % 8;
        loc[i].y = (rand() - j) % 8;
        for (k = 0; k < i; k++)         // check in already created coordinates
            if(loc[i].x == loc[k].x && loc[i].y == loc[k].y)
                break;
        if(k == i)                      // no match found
            i++;                        // create next coordinates[i]
                                        //   otherwise create coordinates again
    }

【讨论】:

  • 就像有无限迭代:/.
  • 现在我得到了至少 2 次相同的坐标。
  • 对不起,我只是从原始帖子中复制错字(函数和循环中的变量名称相同)。代码已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 2021-10-03
  • 1970-01-01
相关资源
最近更新 更多