Created
April 1, 2018 13:56
-
-
Save azamatsmith/64180cf320f859655ffa9595749bf556 to your computer and use it in GitHub Desktop.
Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your …
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
// Inspired by the movie 21. I wanted to run a simulation to better understand the | |
// problem and test to see if the odds really do shift to 66%. | |
// Spoiler Alert: They do! | |
// NOTE: Also swapped llamas for goats since they are way cooler | |
// Generate a random number between 1 and 3 | |
function getNum() { | |
return Math.floor(Math.random() * 3) + 1 | |
} | |
// Build array of selections | |
const doorWithCar = Array(1000) | |
.fill('') | |
.map(() => { | |
return getNum() | |
}) | |
// Objects that hold the cound of right and wrong answers | |
const noSwitch = { | |
right: 0, | |
wrong: 0, | |
} | |
const doesSwitch = { | |
right: 0, | |
wrong: 0, | |
} | |
function openLlamaDoor(doorWithCar, chosen) { | |
// cannot open the door with a car | |
// cannot open the door that the person chose | |
// need to "getNum" until door is not door with car or chosen door | |
let openedDoor = null | |
do { | |
openedDoor = getNum() | |
} while (openedDoor === doorWithCar || openedDoor === chosen) | |
return openedDoor | |
} | |
function checkSwitch(selection, car, llama) { | |
let vals = [1, 2, 3] | |
// remove llama | |
const llamaIndex = vals.indexOf(llama) | |
vals.splice(llamaIndex, 1) | |
const selectionIndex = vals.indexOf(selection) | |
vals.splice(selectionIndex, 1) | |
const switchSelection = vals[0] | |
switchSelection === car ? (doesSwitch.right += 1) : (doesSwitch.wrong += 1) | |
} | |
function checkNoSwitch(selection, car) { | |
selection === car ? (noSwitch.right += 1) : (noSwitch.wrong += 1) | |
} | |
doorWithCar.forEach(car => { | |
// choose a door | |
const thisChoice = getNum() | |
const llamaDoor = openLlamaDoor(car, thisChoice) | |
checkNoSwitch(thisChoice, car) | |
checkSwitch(thisChoice, car, llamaDoor) | |
console.log('Did Not Switch', noSwitch) | |
console.log('Did switch', doesSwitch) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment