Monty Hall Simulation

Three doors, 2 have goats behind them, 1 has a car. After making a choice, you are shown a door that has a goat. Do you change your choice? Answer is yes you should, boosts odds of winning from 33% to 50%.

by Kaeden

JavaScript

const generateDoors = () => {
	const values = [false, false, false];
  
  const carDoor = Math.floor(Math.random() * 3);
  values[carDoor] = true;
  
  return values;
}

const runRound = (roundNum, wins) => {
	const doors = generateDoors();
  console.log('doors =', JSON.stringify(doors));
  
  let choiceIndex = Math.floor(Math.random() * 3);
  
	const someGoatDoorIndex = (doors.map((value, index) => [value, index]).filter(([value, index]) => value === false && index !== choiceIndex).map(([value, index]) => index))[Math.floor(Math.random() * 2)];
console.log('someGoatDoorIndex = ', JSON.stringify(someGoatDoorIndex));


  const remainingDoorIndices = doors.map((value, index) => [value, index]).filter(([value, index]) => index !== someGoatDoorIndex).map(([value, index]) => index);
  console.log('remainingIndices = ', JSON.stringify(remainingDoorIndices));
  
  // stick with original choice -- disabled, gives approx 33% win rate
  // choiceIndex = choiceIndex;
  
  // change choice, gives approx 50% win rate
  choiceIndex = doors.map((value, index) => [value, index]).filter(([value, index]) => index !== someGoatDoorIndex && index !== choiceIndex).map(([value, index]) => index)[0];
  
  const win = doors[choiceIndex];
  
  return win;
}

let wins = 0;
for (let i = 0; i < 100; i++) {
	if (runRound()) {
  	wins++;
  }
}

console.log('rounds = 100, wins = ', wins);