c - 生成 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 个随机的唯一坐标。
我将如何实现这一点?
解决方案
如果此处的算法(唯一坐标)有问题,请检查您新创建的坐标与数组中已创建的坐标。
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
}
推荐阅读
- php - 如何将格式为“yyyy-mm-dd to yyyy-mm-dd”的字符串范围解析为开始/结束日期
- javascript - How to open two web pages at once? This is working on all devices with the exception of iPhones
- .net - Can't install .NET Framework 3.5 feature (0x800f0922)
- c++ - 调用堆栈中的访问冲突
- java - 在 for 循环期间从列表中删除对象
- javascript - Is it possible to show only posts with dates older than yesterday
- sql - 如何对两个 SELECT 查询进行除法?
- python - 未能将一些 refs 推送到 heroku
- angular - 如何在 Angular 中显示数据?
- sql - PostgresSQL:备份表作为 UPDATE 语句