Skip to content

Instantly share code, notes, and snippets.

@eienf
Created February 1, 2013 08:20
Show Gist options
  • Save eienf/4690076 to your computer and use it in GitHub Desktop.
Save eienf/4690076 to your computer and use it in GitHub Desktop.
Check code for probability.
//
// main.c
// CodeTest
//
// Created by eien.support@gmail.com on 2013/02/01.
// Copyright (c) 2013 Eien Factory. All rights reserved.
//
#include <stdio.h>
#include <mach/mach_time.h>
#include <stdlib.h>
int selectOne(int max) {
long value;
value = arc4random();
return value % max;
}
_Bool doTest()
{
const int max = 3;
enum {
kNone = 0,
kWin = 1,
kOpen = 2,
};
int bascket[max] = {kNone};
int winIndex = selectOne(max);
bascket[winIndex] = kWin;
int chooseIndex = selectOne(max);
// printf("win = %d : choose = %d\n",winIndex,chooseIndex);
int openIndex = selectOne(max);
while (openIndex==chooseIndex||openIndex==winIndex) {
openIndex = selectOne(max);
}
bascket[openIndex] = kOpen;
int rechooseIndex = selectOne(max);
while (rechooseIndex==chooseIndex||rechooseIndex==openIndex) {
rechooseIndex = selectOne(max);
}
return (winIndex==rechooseIndex);
}
int main(int argc, const char * argv[])
{
int winFirst = 0;
const int repeat = 10000;
for (int i=0; i<repeat; i++) {
if ( doTest() ) {
winFirst++;
}
}
printf("win if you changed : %d/%d = %f\n",winFirst,repeat,(double)winFirst/(double)repeat);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment