// A Monty Hall Problem Simulation
// https://wokwi.com/projects/472906781803671553
// for https://forum.arduino.cc/t/the-monty-hall-problem/1456367/152
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.print("Press any key to randomize");
while(!Serial.available() ) ;
int key = Serial.read();
randomSeed(random()+micros());
}
long gameCount = 0;
long stayWins = 0;
long switchWins = 0;
long postMontyWins = 0;
long trials = 1000;
void loop() {
char prizes[]= "CER"; // Car, Ewe, Ram
if(trials){
--trials;
scrambleString(prizes);
//Serial.println(prizes);
int carDoorChoice = random(3); // which door is the car hidden behind?
int stayDoorChoice = random(3); // Which door does the "Stay" layer choose
int goatChoice = random(2); // 1st or second goat, if two goats unchoses
int postMontyChoice = random(2); // one of the two remaining doors
++gameCount;
char tmp = prizes[carDoorChoice];
int montyOpens = -1;
int switchDoorChoice = -1;
if (prizes[stayDoorChoice] == 'C' ){
++stayWins;
// two goats for Monty to choose
switch (stayDoorChoice){
case 0: montyOpens = goatChoice==0? 1 :2; break;
case 1: montyOpens = goatChoice==0? 0 :2; break;
case 2: montyOpens = goatChoice==0? 0 :1; break;
}
if (postMontyChoice == 0) ++postMontyWins;
}
else // stay chose a goat
{
switch (stayDoorChoice){
case 0: montyOpens = prizes[1]!='C'? 1:2;
switchDoorChoice = montyOpens==1? 2:1;
break;
case 1: montyOpens = prizes[0]!='C'? 0:2;
switchDoorChoice = montyOpens==0? 2:0;
break;
case 2: montyOpens = prizes[0]!='C'? 0:1;
switchDoorChoice = montyOpens==0? 1:0;
break;
}
++switchWins;
if (postMontyChoice == 1) ++postMontyWins;
}
Serial.print(" Trial:");
Serial.print(gameCount);
Serial.print(" prizes:");
Serial.print(prizes);
Serial.print(" Stay:");
Serial.print(stayDoorChoice+1);
Serial.print(" Monty:");
Serial.print(montyOpens+1);
Serial.print(" Switch:");
Serial.print(switchDoorChoice+1);
Serial.print(" stay%=");
Serial.print(100.0*stayWins/gameCount);
Serial.print(" switch%=");
Serial.print(100.0*switchWins/gameCount);
Serial.print(" random%=");
Serial.print(100.0*postMontyWins/gameCount);
Serial.println();
}
}
void scrambleString(char* string){
unsigned length = strlen(string);
for (int i = 0; i < length; i++)
{
int random_index = rand() % length; // 0 ... length-1
char temp = string[random_index];
string[random_index] = string[i];
string[i] = temp;
}
}
void BADscrambleString(char* str){
//oops -- don't reinvent the wheel
unsigned ll = strlen(str)-1;
for(long ii = ll; ii >0 ; --ii){
int ind = random(ii);
char temp = str[ind];
str[ind]= str[ll];
str[ll] = temp;
}
}