Last active
March 29, 2017 13:48
-
-
Save carlossless/310ca35fedac08191142 to your computer and use it in GitHub Desktop.
A statistical simulation of the Monty Hall problem.
This file contains hidden or 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
#include <stdlib.h> | |
#include <stdio.h> | |
#include <time.h> | |
int rand_lim(int limit); | |
int try_game(); | |
int main () | |
{ | |
srand(time(NULL)); | |
int sum = 0; | |
int i; | |
for (i = 0; i<10000000; i++) { | |
int result = try_game(); | |
sum += result; | |
} | |
printf("%f\n", sum / (float)i); | |
return 0; | |
} | |
int try_game() | |
{ | |
int car = rand_lim(2); | |
int chosen = rand_lim(2); | |
int revealed = (rand_lim(1) + chosen + 1) % 3; | |
revealed = (revealed == car) ? ((revealed + 1) % 3) : revealed; | |
revealed = (revealed == chosen) ? ((revealed + 1) % 3) : revealed; | |
int rechose = (revealed + 1) % 3; | |
rechose = (rechose == chosen) ? ((chosen + 1) % 3) : rechose; | |
if (chosen == revealed || revealed == car || chosen == rechose) { | |
printf("%d %d %d %d\n", car, chosen, revealed, rechose); | |
exit(1); | |
} | |
return car == rechose; | |
} | |
int rand_lim(int limit) | |
{ | |
int divisor = RAND_MAX/(limit+1); | |
int retval; | |
do { | |
retval = rand() / divisor; | |
} while (retval > limit); | |
return retval; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment