Page 1 of 1

random numbers

Posted: Sun Jun 13, 2010 10:21 pm
by Randi
I have a program that generates random numbers, for an array of classes, when I initialize the array it sets 2 variables to random integers. The problem I am having is the random integers are always the same for each instance of the class. I am currently using a do while loop to check to see if the numbers are the same, but the program takes a couple seconds until the integers are set, is there a faster way of doing this?

Code: Select all

player::player()
{
srand(static_cast<unsigned int>(time(0)));
health = rand()%50+1;
mana = rand()%70+1;
}

Re: random numbers

Posted: Mon Jun 14, 2010 12:08 am
by X Abstract X
The numbers generated are the same for each instance because the time is probably the same each time you seed, assuming your array of players is small and takes little time to initialize.

You could seed once at the start of your program using the current time and generate all of the numbers without seeding again.

Re: random numbers

Posted: Mon Jun 14, 2010 12:24 am
by Live-Dimension
No one can really tell you whats wrong without more code. I for one can't see an issue.

Random number generators aren't really that random. They are just a bunch of operations designed to look like they give a random number. They all start out from a chosen seed, usually it's the ms since unix epoch, or something similar. As such, giving the same seed to a RNG will give the same "random" number. I assume that's what is going on here.

Re: random numbers

Posted: Mon Jun 14, 2010 4:35 am
by ismetteren
This may be a bit offtopic, but I recently found this site which seems pretty cool: http://www.random.org it generates random numbers from atmospheric noise and im pretty sure it has an API. This is probably an overkill, but it is also pretty cool :D

Re: random numbers

Posted: Mon Jun 14, 2010 3:02 pm
by Scoody
Just seed it once, ie. in main before anything else is initialized. Don't put it in a constructor that's called more than once like your player-class, as I understand.

Re: random numbers

Posted: Mon Jun 14, 2010 3:35 pm
by avansc
im not sure what time gives, but if it give it in seconds, and you are initializing all the classes in a loop, you are seeding all of them with the same time.

Re: random numbers

Posted: Mon Jun 14, 2010 6:15 pm
by Live-Dimension
Exactly, this is what I failed to say last time. Hell, even ms since epoch is not enough. Some RNG's will change the seed each time since last use (Probably by adding/multiplying the last random number).