#include
#include
#include
using namespace std;
/*
* This program was written to help introduce the use of (pseudo) random
* numbers. The code was also used to introduce the topic of date and time.
*
* @creator gdt
* @created 02016.10.31
* @version 02016.11.02
* @edu This program was introduced because the more recently
* assigned programming assignment was a guessing game
* that required the use of random numbers.
*
* Introducing date and time resulted in an introduction
* to typedef (what is time_t?).
*/
int main(int, char**) {
const int HOW_MANY_RANDOM_NUMBERS = 50000;
const int MIN_RANDOM_NUMBER = 0;
const int MAX_RANDOM_NUMBER = 100;
// srand(42); // 1st used a fixed "seed"; 42 was an arbitrary choice
time_t t = time(NULL); // NULL, time(NULL), time_t explained...
cout << "time = " << t << endl;
srand(t); // 2nd used a "seed" that is current time based
// print out maximum random number returned from rand()...
//
cout << "RAND_MAX = " << RAND_MAX << endl;
// generate randon numbers n such that 0 <= n <= 100
// and keep a count of how many times each random number
// is generated (demonstrates pseudo-random number generation)
// [note: demonstrates using an array as a collection of counters]
//
int counts[MAX_RANDOM_NUMBER + 1] = { 0 }; // all ints set to 0
for (int i = 0; i < HOW_MANY_RANDOM_NUMBERS; i++) {
int r = rand() % (MAX_RANDOM_NUMBER + 1);
counts[r]++;
}
// the following loop was added to demonstrate that we did
// indeed generated HOW_MANY_RANDOM_NUMBER random numbers...
//
int sum = 0;
for (int i = 0; i <= MAX_RANDOM_NUMBER; i++) {
cout << "counts[" << i << "] = " << counts[i] << endl;
sum += counts[i];
}
cout << "# of random numbers counted: " << sum << endl;
}