Home > Net >  How do i create an array with n elements where values are between 0 and n without duplicates?
How do i create an array with n elements where values are between 0 and n without duplicates?

Time:01-03

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.

CodePudding user response:

Your description of your requirement is ambiguous, but your code appears to be an attempt at a randomly ordered sequence of values from 1 to n inclusive.

That being the case, a simpler and more deterministic method than picking a random number than checking if it has already been used is simply to generate the values sequentially, then shuffle the array.

    // Create an array of n elements
    int* r = malloc( n * sizeof(*r) ) ;
    
    // Fill the array with values 1 to n
    for( size_t i = 0; i < n; i   )
    {
        r[i] = i   1 ;
    }
    
    // Shuffle the array
    for( size_t i = 0; i < n - 1; i  ) 
    {
        size_t j = i   rand() / (RAND_MAX / (n - i)   1);
        int t = r[j];
        r[j] = r[i];
        r[i] = t;
    }

CodePudding user response:

You logic is sound albeit not very efficient.

But you're missing an array and your loops don't work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main ()
{
    srand(time(NULL));
    int r[8];  // this is an array
    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])   // if duplicate
            {
                i--;        // go back
                break;      // and try again
            }
        }
    }
    for (int i=0; i<n; i  ) printf ("%d,",r[i]);
    printf ("\n");
}
  • Related