Random Numbers
- Random numbers are generated with pre-defined functions
- Psuedo-random numbers:
- The random numbers generated by the pre-defined functions are actually
provided from a pre-computed table of random numbers, i.e., they are
looked-up not produced on the spot.
- The implication of this is that if you want a different random string
between two executions, you need to begin at a random location in the table.
- Seeding the generator:
- The process of figuring out where to begin in the table is called "seeding
the random number generator"
- Example: srand((unsigned int) time(0));
- Generating a random number:
- Example: int randomNumber = rand();
- Generating a number within a range:
- The numbers generated by rand() are between 0 and MAX_INT, but what if you
want a number between 1 and 100, what do you do?
- The modulus function reduces all numbers to be between zero and the
modulus.
- For example: int num = rand() % 100 give a number, num, between 0
and 99.
- Add a 'base' to shift the range: e.g., int newNum = rand() % 100 +
1;
- Random Number Generation