Created
June 17, 2010 13:15
-
-
Save jorgeatorres/442096 to your computer and use it in GitHub Desktop.
Monty Hall problem simulator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Monty Hall problem. | |
* http://en.wikipedia.org/wiki/Monty_Hall_problem | |
*/ | |
#include <stdio.h> | |
#ifdef DEBUG | |
#define verbose printf | |
#else | |
#define verbose | |
#endif | |
typedef unsigned long ulong; | |
int main(int argc, char **argv) | |
{ | |
int games = 1000000; | |
ulong wins_sticker = 0, wins_switcher = 0; | |
/* Parse args. */ | |
if (argc == 2) { | |
games = atoi (argv[1]); | |
} | |
srand (time (0)); | |
int i; | |
for (i = 0; i < games; i++) { | |
int car, contestant, monty; | |
verbose("\n--> GAME NO. %d\n", i); | |
/* Place the car behind one door at random. */ | |
car = rand() % 3; | |
/* Contestant picks a door. */ | |
contestant = rand() % 3; | |
/* If contestant has chosen the prize, Monty picks another door at random. | |
* Otherwise, Monty picks the other goat. */ | |
if (contestant == car) { | |
monty = (contestant + (rand() % 2) + 1) % 3; | |
} else { | |
monty = (((contestant + 1) % 3) == car) ? ((contestant + 2) % 3) : ((contestant + 1) % 3); | |
} | |
verbose("Car's behind door %d, Contestant opens %d, Monty opens %d\n", car, contestant, monty); | |
if (contestant == car) { | |
wins_sticker++; | |
verbose("Sticker wins.\n"); | |
} else { | |
wins_switcher++; | |
verbose("Switcher wins.\n"); | |
} | |
} | |
printf("%d games played:\n", games); | |
printf("Sticker has won %d times (%0.02f\%)\n", wins_sticker, ((double) wins_sticker / games * 100)); | |
printf("Switcher has won %d times (%0.02f\%)\n", wins_switcher, ((double) wins_switcher / games * 100)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment