首页 > 解决方案 > 生成 8 种不同的坐标

问题描述

我正在尝试编写一个获取数组的函数,生成 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 个随机的唯一坐标。

我将如何实现这一点?

标签: crandomsrand

解决方案


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

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
    }

推荐阅读