Pergunta

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

Foi útil?

Solução 2

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.

Outras dicas

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.

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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top