1

I have an array of six random numbers from 1-49 so far but some repeat eg, 12 15 43 43 22 15 is there a way around this problem?

so far I have...

int* get_numbers()
{
        int Array[6], i;
        printf("\n\n Your numbers are : ");
        for (i = 0; i < 6; i++)
        {
               Array[i] = ((rand() % 49) + 1);
               printf("%d ",Array[i]);
        }
}

any feedback will be great, thanks

Kevin
  • 53,822
  • 15
  • 101
  • 132
  • What is the problem you are trying to solve? Do you need 6 unique numbers? –  Mar 19 '14 at 18:08

4 Answers4

2

You could simply throw out duplicates.

Another option would be to create an array of numbers 1-49, shuffle them, and take the first 6.

Community
  • 1
  • 1
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

You need to add a separate loop that goes from 0, inclusive, to i, exclusive, checking the candidate number against the numbers that have been added to the array before. If the check finds a duplicate, do not increment i, and try generating a random number again:

int i = 0;
while (i != 6) {
   int candidate = ((rand() % 49) + 1);
   int ok = 1; // ok will become 0 if a duplicate is found
   for (int j = 0 ; ok && j != i ; j++) {
       ok &= (candidate != Array[j]);
   }
   if (ok) {
       Array[i++] = candidate;
       printf("%d ", candidate);
   }
}

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The rand function is not aware of its previous output so you can put a check before you save it in the array

Am_Sri
  • 19
  • 1
  • 3
0

If you get the first random number as x, find the second random number as the random of random(1 to x-1) and random(x+1 to n). Continue in this way.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33