Now I don't remember where I read this, but I recall that rand() works with the clock in some way |
You are mistaken. rand() does not use the clock in any way.
You can use rand just fine for what you are trying to do.
LONG AND LENGTHY EXPLANATION OF HOW PRNGS WORK
PRNGs are basically a mathematical operation designed to take an input number and "scramble it" to produce an output number that looks random.
The output number is then used as the next iteration's input... so it produces a sequence of semi-random numbers.
For example... rand() might look something like this (note: this is conceptual, rand probably looks very different):
1 2 3 4 5 6 7
|
int rand_state = 0; // <- state of the RNG (input and output)
int rand()
{
rand_state = rand_state * 46781267 + 9788973; // scramble the number
return rand_state;
}
|
This will produce random-looking numbers, however the sequence will always be the same because the starting point (rand_state) is always zero. Therefore you must "seed" the PRNG so that it starts at a different point in the sequence. This is what the 'srand' function is for:
1 2 3 4
|
void srand(int seed)
{
rand_state = seed;
}
|
Now... this is where the clock comes in. People usually use the current time to seed the RNG because the clock is almost guaranteed to be different each time the program is run. This ensures that you'll start at a different point in the random sequence, which means you'll get a different stream of random numbers each time the program is run.
example:
1 2 3 4 5 6 7 8
|
int main()
{
srand( time(0) ); // <- seed with the current time
// print 5 different random numbers:
for(int i = 0; i < 5; ++i)
cout << rand() << endl;
}
|
The
problem is that newbies don't understand the difference between srand and rand... and think you have to call them together (when you
shouldn't). Thus they often do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int random()
{
// never do this
srand( time(0) );
return rand();
}
int main()
{
// generate 5 random numbers (poorly)
for(int i = 0; i < 5; ++i)
cout << random() << endl;
}
|
If you do this... you
will get the same number repeated, because you keep resetting the rng with srand after each call to rand... ensuring that it will start at the same point in the sequence (and therefore produce the same number) as it did previously.
So as long as you call srand() exactly
once at the start of your program... then rand() will work just fine for your purposes. It may not be the best rng around, but it's decent and is beginner friendly.