lundi 2 janvier 2023

How do i create an array with n elements where values are between 0 - n without duplicates?

I want to give an array of a specific length a random number generated to each elements value where the values are varying.

srand(time(NULL));
int r;
int n = 8; //n is given for the sake of this example
for (int i = 0; i < n; i++)
{
  r[i] = (rand() % n) + 1;
  for (int j = 0; j < i; j++)
  {
    if (r[i] != r[j])
    {
     return 0;
    }
    else
    {
      while (r[i] == r[j])
      {
        r[i] = (rand() % n) + 1;
      }
   }
}

The problem is that the while loop doesn't go through every single element in the array "r" which most likely will give the array multiple elements with the same value since it only checks for one element and not the ones before.

In conclusion I need help to check for all elements and somehow eliminate the ones already chosen.




Aucun commentaire:

Enregistrer un commentaire