Created
February 1, 2013 08:20
-
-
Save eienf/4690076 to your computer and use it in GitHub Desktop.
Check code for probability.
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
// | |
// main.c | |
// CodeTest | |
// | |
// Created by [email protected] 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