In Germany we have a lottery with the following rules:
You have to guess 6 numbers. The numbers shall be less than 50 and greater then 0. A number occurs only one time in a game. So you can not guess the same number multiple times in one game. If you have guessed 6 numbers right you won the game.
I wanted to know how many attempts it would take to have 6 right numbers and wrote this example. It works but unfortunately the example is very slow and needs a lot of time because it is very unlikely to have 6 numbers right. How could I improve the speed?
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int play(int attempt[])
{
// generate draw
int draw[6];
draw[0] = rand() % 49 + 1;
for(int i = 1; i < 6; i++)
{
int random_number;
generate:
random_number = rand() % 49 + 1;
for(int j = 0; j < i; j++)
{
if(random_number == draw[j])
{
goto generate;
}
}
draw[i] = random_number;
}
// compare draw with attempt
int compared = 0;
for(int i = 0; i < 6; i++)
{
if(attempt[i] == draw[i])
{
compared++;
}
}
if(compared == 6)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
srand (time(NULL));
int attempt[] = {1, 2, 3, 4, 5, 6};
long long int counter = 1;
while(!play(attempt))
{
counter++;
}
printf("You only needed %lld attempts to get 6 right numbers!\n", counter);
}
By the way: after around 5 minutes the program was finished and I needed only 1,487,592,156 attempts!