terça-feira, 4 de agosto de 2015

Another way to initialize a random generator in C++

If you have several programs generating random seeds at nanosecond difference, you could experiment the same output of rand() function.

An alternative way could be:

int R=0;

long long Temp=(long long)&R;

// Initialize the random generator
srand ((unsigned int)Temp);

Every program puts the R variable in a different portion of the memory, so conflict is minimized for programs starting at the same time, for example.

If you are concerned that two computers could allocate the variable R exaclty at the same memory position, then you can do:

#ifndef _TIME_H
#include


long long Temp=(long long)&R;
 

// Initialize the random generator
lsrand ((unsigned int)Temp*time(NULL));
 

// Generates a integer random number
R=1+(rand()%2147483647);


Nenhum comentário: