Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Monty Hall problem simulator v2
- *
- * Compile with g++:
- * $ g++ montyhall.cc -o montyhall
- */
- #include <iostream>
- #include <stdlib.h>
- #include <time.h>
- using namespace std;
- void PrintDoors(int car, int chosenDoor, bool*opened);
- int main()
- {
- srand((unsigned)time(NULL));
- unsigned int wins=0, winsSwitch=0, numSwitches=0;
- for(unsigned int game=1;;++game) {
- int car = rand()%3;
- bool opened[3] = {0,0,0};
- int chosenDoor, chooseSwitch;
- cout << "Game " << game << endl << "---------" << endl;
- //Contestant chooses initial door
- PrintDoors(car, -1, opened);
- do {
- cout << "Choose a door (1,2,3): ";
- cin >> chosenDoor ;
- } while(chosenDoor<1 || chosenDoor>3);
- --chosenDoor;
- //Monty opens door
- if(chosenDoor==car)
- opened[ (car + rand()%2 + 1) % 3 ] = 1;
- else if((chosenDoor+1)%3 != car)
- opened[ (chosenDoor+1)%3 ] = 1;
- else
- opened[ (chosenDoor+2)%3 ] = 1;
- cout << endl;
- PrintDoors(car, chosenDoor, opened);
- //Record result for switching
- if(chosenDoor != car)
- ++winsSwitch;
- //Contestant chooses to switch or stick
- do {
- cout << "Stick (0) or switch (1)?: ";
- cin >> chooseSwitch;
- } while(chooseSwitch<0 || chooseSwitch>1);
- if(chooseSwitch==1) {
- if(!opened[(chosenDoor+1)%3])
- chosenDoor = (chosenDoor+1)%3;
- else
- chosenDoor = (chosenDoor+2)%3;
- ++numSwitches;
- }
- //Find game result
- opened[0] = opened[1] = opened[2] = 1;
- cout << endl;
- PrintDoors(car, chosenDoor, opened);
- cout << endl;
- if(chosenDoor==car) {
- cout << "*** You win the car! ***" << endl << endl;
- ++wins;
- } else
- cout << "*** You win a goat. ***" << endl << endl;
- cout << "In " << game << " game" << (game==1?"":"s") << ", with "
- << (game-numSwitches) << " stick" << (game-numSwitches==1?"":"s") << " and " << numSwitches << " switch" << (numSwitches==1?"":"es")
- << ", you won " << wins << " cars " " => "
- << 100*static_cast<float>(wins)/game << "% success" << endl;
- cout << "By sticking every time, you would have won " << game - winsSwitch << " car" << (game-winsSwitch==1?"":"s") << " => " << 100*static_cast<float>(game - winsSwitch)/game << "% success" << endl;
- cout << "By switching every time, you would have won " << winsSwitch << " car" << (winsSwitch==1?"":"s") << " => " << 100*static_cast<float>(winsSwitch)/game << "% success" << endl << endl;
- }
- return 0;
- }
- void PrintDoors(int car, int chosenDoor, bool*opened)
- {
- for(int door=0; door<3; ++door) {
- cout << door+1;
- if(door == chosenDoor)
- cout << "*";
- else
- cout << " ";
- if(!opened[door])
- cout << "[x]";
- else if(car!=door)
- cout << "[Goat]";
- else
- cout << "[Car]";
- cout << " ";
- }
- cout << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement