Skip to content

Instantly share code, notes, and snippets.

Created February 17, 2015 06:57
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 anonymous/b3e0a653097e61bec498 to your computer and use it in GitHub Desktop.
Save anonymous/b3e0a653097e61bec498 to your computer and use it in GitHub Desktop.
// C program to verify the solution to "The Three Hats Game"
// as seen on http://www.futilitycloset.com/2015/02/17/the-three-hats-game/
// Compile with gcc -o hat-game hat-game.c
//
// Count wins: ./hat-game | grep win | wc -l
// Count losses: ./hat-game | grep lose | wc -l
#include <stdio.h>
#include <stdlib.h>
void game() {
int r = rand();
int a = r & 1;
int b = (r & 2) ? 1 : 0;
int c = (r & 4) ? 1 : 0;
printf("a:%d b:%d c:%d ", a, b, c);
// How many players guessed
int guessed = 0;
int wrong = 0;
// a's choice
if (b ^ c) {
// Saw different colors
printf("A:- ");
} else {
guessed++;
int guess = !b;
printf("A:%d ", guess);
if (a != guess) wrong = 1;
}
// b's choice
if (a ^ c) {
// Saw different colors
printf("B:- ");
} else {
guessed++;
int guess = !a;
printf("B:%d ", guess);
if (b != guess) wrong = 1;
}
// c's choice
if (a ^ b) {
// Saw different colors
printf("C:- ");
} else {
guessed++;
int guess = !b;
printf("C:%d ", guess);
if (c != guess) wrong = 1;
}
if (guessed > 0 && !wrong) {
printf(" = win\n");
} else {
printf(" = lose\n");
}
}
int main(int argc, char **argv) {
srand(42);
int i;
for (i = 0; i < 10000; i++) { game(); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment