Skip to content

Instantly share code, notes, and snippets.

@stut
Last active April 12, 2016 00:44
Show Gist options
  • Save stut/8991b7dcd9743d124ef1e16ff38adfb9 to your computer and use it in GitHub Desktop.
Save stut/8991b7dcd9743d124ef1e16ff38adfb9 to your computer and use it in GitHub Desktop.
Test the Monty Hall problem
#include <stdio.h>
#include <stdlib.h>
#define rand3() ((int)(rand() % 3)+1)
void seedrand()
{
unsigned int randval;
FILE *f;
f = fopen("/dev/random", "r");
fread(&randval, sizeof(randval), 1, f);
fclose(f);
srand(randval);
}
inline bool play()
{
int car = 0;
int choice = 0;
int opened = 0;
// Assign the car.
car = rand3();
// Make the initial choice.
choice = rand3();
// Open a door.
while (opened == 0 || opened == choice || opened == car) {
opened = rand3();
}
// Change our choice.
if (choice != 1 && opened != 1) {
choice = 1;
} else if (choice != 2 && opened != 2) {
choice = 2;
} else {
choice = 3;
}
return choice == car;
}
int main()
{
seedrand();
int count = 10000000;
int wins = 0;
for (int i = 0; i < count; i++) {
if (play()) {
wins += 1;
}
}
printf("Won %.4g%%\n", (((double)wins) / count) * 100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment