Created
July 12, 2022 20:26
-
-
Save 0wx/ea82e4afe45296f19462fd6560088c39 to your computer and use it in GitHub Desktop.
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
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