// // Program name: roll_dice_v2 // Author: B. Massingill // // 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 int main() { bool faces[6] ; // faces[i] is true if we've // seen face i int rolls ; // number of rolls so far int numFacesSeen ; // number of distinct faces // seen so far int faceThisRoll ; // face displayed by current // roll int trials = 0 ; // trials performed so far int trialsRequested ; // trials requested by user double sumOfResults = 0.0 ; // sum of results of trials // so far // (why double? (1) to make // it easier to print // non-integer average, // and (2) to allow // really big numbers -- // if we choose) int i ; // counter for initialization cout << "How many trials do you want to perform?\n" ; cin >> trialsRequested ; trials = 0 ; while (trials < trialsRequested) { // (re)initialize rolls = 0 ; numFacesSeen = 0 ; i = 0 ; while (i < 6) { faces[i] = false ; i++ ; } // now roll the die repeatedly until we've seen all // faces while (numFacesSeen < 6) { // "roll the die": generate a random number // between 0 and 5 rolls += 1 ; faceThisRoll = 1 + (int) ((6.0 * rand())/(RAND_MAX + 1.0)) ; if (!faces[faceThisRoll - 1]) { // face we haven't seen before faces[faceThisRoll - 1] = true ; numFacesSeen += 1 ; } } // done with this trial trials += 1 ; // uncomment the following lines to see the results // of each trial // cout << rolls << " rolls were required in trial " << // trials << endl ; sumOfResults += rolls ; } // all done; print results if (trialsRequested > 0) cout << "Average number of trials was " << sumOfResults / trialsRequested << endl ; else cout << "No trials requested\n" ; return 0 ; }