Published
Edited
Sep 17, 2020
Insert cell
md`# Monty Carlo`
Insert cell
PRIZE = {
return {
DONKEY: 0,
SPORTSCAR: 1
}
};
Insert cell
getIndex = {
return () => Math.floor(Math.random() * 3)
}
Insert cell
getDoors = {
return () => {
const index = getIndex()
return Array.from({ length: 3 }, (_, i) => i === index ? PRIZE.SPORTSCAR : PRIZE.DONKEY)
}
}
Insert cell
playGame = {
return () => {
const doors = getDoors()
const guess = getIndex()
const openedDoor = doors.findIndex((p, i) => i !== guess && p === PRIZE.DONKEY)
const changedGuess = doors.findIndex((_, i) => ![guess, openedDoor].includes(i))
return doors[changedGuess] === PRIZE.SPORTSCAR
}
}
Insert cell
winPercentage = {
const numberOfGames = 10000000
const games = Array.from({ length: numberOfGames }, () => playGame())
const toWinsAndLosses = ([wins, losses], playerWon) => playerWon ? [wins + 1, losses] : [wins, losses + 1]
const [wins, losses] = games.reduce(toWinsAndLosses, [0, 0])
return (wins / numberOfGames) * 100
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more