我正在试着写一个获取数组的函数,生成8个不同的坐标。我有一些大小为8的struct Array,它将一些坐标保存在另一个数组(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个随机的唯一坐标。
我该如何实现它呢?
发布于 2020-12-09 19:36:58
如果这里的算法(唯一坐标)有问题,请用数组中已经创建的坐标检查新创建的坐标。
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
}https://stackoverflow.com/questions/65212765
复制相似问题