// // Program name: roll_dice_v2 // // Program to estimate how many times one must roll a 6-sided die // before seeing all its faces. // // The program performs repeated "trials". In each trial, it simulates // rolling a die, and tracks how many rolls are required before // all faces have been seen. It then computes an average number // of rolls over all trials. // // Input: (from standard input) positive integer specifying how many // trials to perform. // Output: (on standard output) the average, over all trials, of the // number of rolls required before all faces of the die have been // seen. // #include #include // has EXIT_SUCCESS, EXIT_FAILURE, // rand() #include // has fill() // Function prototypes. int roll(int numFaces); int doTrial(void); // Main program. int main() { int sumOfResults = 0; // sum of rolls required for each trial int numTrials; cout << "How many trials do you want to perform?\n"; cin >> numTrials; if (numTrials <= 0) { cout << "Number must be positive!\n"; exit(EXIT_FAILURE); } for (int i = 0; i < numTrials; ++i) { int rolls = doTrial(); sumOfResults += rolls; cout << rolls << " rolls were required in trial " << i << endl; } cout << "Average number of trials was " << double(sumOfResults) / double(numTrials) << endl; return EXIT_SUCCESS; } // Function definitions. // Post: returns number of rolls required by this trial. int doTrial(void) { const int FacesOnDie = 6; // total number of faces on die bool seen[FacesOnDie]; // seen[i] is true if we've see face // i, false otherwise. int rolls = 0; // number of rolls so far int numSeen = 0; // number of distinct faces so far int thisRoll; // face displayed by current roll // Initialize seen array. fill (seen, seen + FacesOnDie, false); // Roll the die repeatedly until we've seen all faces. while (numSeen < FacesOnDie) { // "Roll the die": generate a random number between // 1 and FacesOnDie. thisRoll = 1 + roll(FacesOnDie); ++rolls; // cout << "the number is " << thisRoll << endl; if (!seen[thisRoll-1]) { // We haven't seen this face before. seen[thisRoll-1] = true; ++numSeen; } } return rolls; } // Function to "roll a die". // Pre: numFaces is positive. // Post: returns a random integer between 0 and numFaces-1. int roll(int numFaces) { return int(((double(numFaces) * rand())/(RAND_MAX + 1.0))); }