I'm trying to write a function that gets an array, generates 8 different coordinates. I have some struct Array of size 8 that saves some coordinates in another array([8][8]). I'm trying to get eight different coordinates, but unfortunately, sometimes I get the same coordinates.
Here is the code :
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;
}
I understand I can use Fisher–Yates shuffle, but my main problem is that, for example, I can have the coordinates (6,6) once, but I cant have it twice. I need 8 random unique coordinates.
How would I implement this?
If algorithm (unique coordinates) here is a problem check your newly create coordinates with already created coordinates in array.
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
}