How to get really random numbers with 'Rand()' in C?

Asked

Viewed 191 times

3

For a schoolwork, I need to create a game, for which I need to generate a random number to make it fair. In one case, as I will post below, I need to assign a random number between 0 and 2 to modify in the string:

int NUM, AUX;
char PORTAS [0] = {'N', 'N', 'N'};

printf ("Entre com o número de participantes: ");
scanf ("%i", &NUM);

PART JOG [NUM];

for ( AUX = 0 ; AUX < NUM ; AUX++ ){
    ent_info (&JOG [AUX], AUX);
}

AUX = rand () %3;
PORTAS [AUX] = 'S';

The problem is that every time, AUX receives the number 2 and I need to generate two other random numbers besides that. How can I get around this problem? Thank you.

  • Put other parts of the code, especially where the random seed is starting. The problem must be there.

1 answer

2


You’re most likely not initializing the seed to generate the pseudo-random numbers. As this is only for school work the most common way to generate random numbers in C should be sufficient.

You can do something like this:

(...)
srand(time(NULL)); //inicializar semente

int NUM, AUX;
char PORTAS [0] = {'N', 'N', 'N'};

printf ("Entre com o número de participantes: ");
scanf ("%i", &NUM);

PART JOG [NUM];

for ( AUX = 0 ; AUX < NUM ; AUX++ ){
    ent_info (&JOG [AUX], AUX);
}

AUX = rand () %3;  //Numero aleatório entre 0 e 2
PORTAS [AUX] = 'S';

There are other alternatives/algorithms for generating random numbers. If you need something with "better" quality compared to the stdlib library solution, you can use "Mersenne Twister" for example. It is quite fast and easily find an implementation. For example here.

For more information you can always check the page: https://en.wikipedia.org/wiki/Mersenne_Twister

Browser other questions tagged

You are not signed in. Login or sign up in order to post.