In: Computer Science
C++ questions about Monty Hall Problem, please make sure to divide the program into functions which perform each major task.
Imagine yourself on the set of a game show. You're given the choice of three doors. Behind one of the doors is a car you can drive home in if you guess correctly. Behind the other two doors are goats.
After you initially guess the door, the host of the game show (who knows the door holding the car) opens one of the other doors revealing a goat. He gives you the choice: stick with your original door, or choose the other unopened door.
This problem is reminiscent of a Sixties game show hosted by an individual named Monty Hall. For this assignment you will write a program simulating this game and the results of either choice. You will ask the user how many times they wish to run the simulation. If the user enters 1000 for instance, your program will run through 1000 simulations where the player sticks with the original door and 1000 simulations where the player chooses the other unopened door. After the program is completed execution, the winning percentages will then be displayed for each strategy. (Be sure to make the initial selection, Monty's selection, and the second-chance selection happen randomly.)
Be sure to divide your program into functions which perform each major task. (The purpose of this assignment is to find out whether or not it's to the player's advantage to change their selection.)
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int randint(int n) { return (1.0*n*std::rand())/(1.0+RAND_MAX); } int other(int doorA, int doorB) { int doorC; if (doorA == doorB) { doorC = randint(2); if (doorC >= doorA) ++doorC; } else { for (doorC = 0; doorC == doorA || doorC == doorB; ++doorC) { // empty } } return doorC; } int check(int games, bool change) { int win_count = 0; for (int game = 0; game < games; ++game) { int const winning_door = randint(3); int const original_choice = randint(3); int open_door = other(original_choice, winning_door); int const selected_door = change? other(open_door, original_choice) : original_choice; if (selected_door == winning_door) ++win_count; } return win_count; } int main() { std::srand(std::time(0)); int games = 10000; int wins_stay = check(games, false); int wins_change = check(games, true); cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n"; }