【发布时间】: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 个随机的唯一坐标。
我将如何实现这个?
【问题讨论】:
-
初始化每一行/列
0 - 7,然后shuffle每一行。见Fisher–Yates shuffle