Skip to content

Instantly share code, notes, and snippets.

@0wx
Created July 12, 2022 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0wx/ea82e4afe45296f19462fd6560088c39 to your computer and use it in GitHub Desktop.
Save 0wx/ea82e4afe45296f19462fd6560088c39 to your computer and use it in GitHub Desktop.
const shuffle = (array: Array<any>) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
const getDoors = (): Array<{ door: number; price: "car" | "goat" }> => {
return shuffle(["car", "goat", "goat"]).map((price, door) => ({
price,
door,
}))
}
const getChoice = (): number => {
return Math.floor(Math.random() * 3)
}
const door = () => {
const doors = getDoors()
const choice = getChoice()
const myDoor = doors[choice]
const otherDoors = doors.filter((_v, i) => i !== choice)
const goatDoor = otherDoors.find((v) => v.price === "goat")!
const otherDoor = otherDoors.find((v) => v.door !== goatDoor.door)!
return { myDoor, otherDoor }
}
const play = () => {
let winWithNoChange = 0
let winWithChangeDoor = 0
for (let i = 0; i < 1e4; i++) {
const { myDoor, otherDoor } = door()
if (myDoor.price === "car") {
winWithNoChange++
} else {
winWithChangeDoor++
}
}
console.log(`winWithNoChange: ${winWithNoChange}`)
console.log(`winWithChangeDoor: ${winWithChangeDoor}`)
}
play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment