A Brief Overview of the Random Number Generator

In order to set up the grid for each mine, you need some way of randomly deciding where to place mines. C provides a pseudo-random number generator function that will help you do this. The function is called rand(). It takes no arguments and returns an integer between 0 and RAND_MAX (a big number that you don't need to worry about.) For example:

int randomNum;
randomNum = rand();

rand() is a "pseudo-random" number generator, because the values that it returns are not exactly random. This is because the computer has to get a number from somewhere - it can't just make one up. rand() uses a sequence of mathematical steps to come up with a number. The advantage of this is that we can repeat a given sequence of "random" numbers. (This can be very helpful for debugging your programs.) To start up the pseudo-random number generator, you need to give it a "seed" value. This value will be the basis for the steps rand() uses to generate numbers. If you give it a different seed every time you start the program, you will get different random numbers. If you give it the same seed, or don't give it a seed at all, you will get the same "random" numbers every time. (This is why it's called "pseudo-random.")

To provide a "seed" value, you use a function called srand(). It takes one integer parameter and does not return anything. If you want to generate the same random numbers over and over (which might be useful at first when you are debugging your program, but might not be what you want for the final game) then don't call srand() at all. If you want really random numbers (well, as close as we can get to random), then you need to call srand with a different seed every time. Here's one way to do that:

srand(time(NULL));

Don't worry about what this means, exactly. Just remember that if you want to have different random numbers every time you run the program, put this line somewhere near the beginning of main().

The prototype for rand() is in the stdlib.h header file. You will need to include this file in your program. You may also want to use the time() function to initialize the random number generator as in the example above. This function is prototyped in time.h. Both of these files are already included in the hw5_orig.c file. Don't remove these #include's if you're planning to use these functions.

Now you know how to get random numbers between 0 and something huge. The next step is transforming them into random number between 0 and some maximum that you choose. It's easy: you just use the % (mod) operator. Remember, for any positive integers a and b, a % b is between 0 and b-1. For example, to get a random number between 0 and 4 (including 0 and 4 as possible values), you say:

randomNum = rand() % 5;