< Previous | Contents | Next >

Seeding the Random Number

Generator

Computers generate pseudorandom numbersnot truly random numbersbased on a formula. One way to think about this is to imagine that the computer reads from a huge book of predetermined numbers. By reading from this book, the computer can appear to produce a sequence of random numbers.

But theres a problem: The computer always starts reading the book from the beginning. Because of this, the computer will always produce the same series of randomnumbers in a program. In games, this isnt something wed want. We wouldnt, for example, want the same series of dice rolls in a game of craps every time we played.

A solution to this problem is to tell the computer to start reading from some arbitrary place in the book when a game program begins. This process is called

Generating Random Numbers 71


seeding the random number generator. Game programmers give the random number generator a number, called a seed, to determine the starting place in this sequence of pseudorandom numbers.

The following code seeds the random number generator:


srand(static_cast<unsigned int>(time(0))); //seed random number generator


Wow, thats a pretty cryptic looking line, but what it does is simple. It seeds the random number generator based on the current date and time, which is perfect since the current date and time will be different for each run of the program.

In terms of the actual code, the srand() function seeds the random number generatoryou just have to pass it an unsigned int as a seed. What gets passed to the function here is the return value of time(0)a number based on the current system date and time. The code static_cast<unsigned int> just converts (or casts) this value to an unsigned int. Now, you dont have to understand all the nuances of this line; the least you need to know is that if you want a program to generate a series of random numbers that are different each time the program is run, your program should execute this line once before calls to rand().


Hin t

image

A comprehensive explanation of the various forms of casting a value from one type to another is beyond the scope of this book.

image