An example might help you understand how random numbers work in algorithm development. Here's a number guessing program written in C:
// Number guessing program
#include
#include
#include
// #define RANDOMIZE
int main(int argc, char* argv) {
#ifdef RANDOMIZE
srand(clock());
#endif
printf("Number guessing program. Enter 0 to quit.\n");
while(1) {
unsigned int randomNumber = (rand() % 10) + 1;
unsigned int guessedNumber;
printf("I'm thinking of a number between 1 and 10. Your guess: ");
scanf("%d", &guessedNumber);
if (guessedNumber == 0) {
break;
}
if (randomNumber == guessedNumber) {
printf("Right you are!\n");
} else {
printf("Sorry, the number was %d.\n", randomNumber);
}
}
}
Put the above code in a file called randgame.c, then compile and run the program by typing a.out:
% cc randgame.c
% a.out
Number guessing program. Enter 0 to quit.
I'm thinking of a number between 1 and 10. Your guess: 5
Sorry, the number was 9.
I'm thinking of a number between 1 and 10. Your guess: 4
Sorry, the number was 9.
I'm thinking of a number between 1 and 10. Your guess: 3
Sorry, the number was 4.
I'm thinking of a number between 1 and 10. Your guess: 2
Sorry, the number was 6.
I'm thinking of a number between 1 and 10. Your guess: 1
Sorry, the number was 2.
I'm thinking of a number between 1 and 10. Your guess: 0
%
If you run the program again you'll get the same result. The program generates the same sequence of random numbers every single time. And that's exactly what you need while you're debugging the program. It's impossible to debug a program that is given different data every time it runs.
But now the program is debugged, so let us randomize the generation of random numbers by calling srand with an argument of the processor clock. Do this by uncommenting the "#define RANDOMIZE" line. Now repeat the steps as before, but this time you'll get a different sequence of random numbers. Everytime you run the program the sequence of random numbers will be different, because the processor clock has a different value each time the program runs:
% cc randgame.c
% a.out
Number guessing program. Enter 0 to quit.
I'm thinking of a number between 1 and 10. Your guess: 5
Sorry, the number was 1.
I'm thinking of a number between 1 and 10. Your guess: 4
Sorry, the number was 9.
I'm thinking of a number between 1 and 10. Your guess: 3
Sorry, the number was 9.
I'm thinking of a number between 1 and 10. Your guess: 2
Sorry, the number was 8.
I'm thinking of a number between 1 and 10. Your guess: 1
Sorry, the number was 9.
I'm thinking of a number between 1 and 10. Your guess: 0
%
--Percy
Edited by Percy, : Accidentally hit submit.
Edited by Percy, : Fix typos.
Edited by Percy, : Fix angle brackets on include statements.