Skip to content

Instantly share code, notes, and snippets.

@carlossless
Last active March 29, 2017 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlossless/310ca35fedac08191142 to your computer and use it in GitHub Desktop.
Save carlossless/310ca35fedac08191142 to your computer and use it in GitHub Desktop.
A statistical simulation of the Monty Hall problem.
#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