a monty-hall solution
This file contains 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
// Generate a random integer r with equal chance in min <= r < max. | |
function randomInt(min, max) { | |
var range = max - min; | |
if (range <= 0) { | |
throw new Exception('max must be larger than min'); | |
} | |
var requestBytes = Math.ceil(Math.log2(range) / 8); | |
if (!requestBytes) { // No randomness required | |
return min; | |
} | |
var maxNum = Math.pow(256, requestBytes); | |
var ar = new Uint8Array(requestBytes); | |
while (true) { | |
window.crypto.getRandomValues(ar); | |
var val = 0; | |
for (var i = 0;i < requestBytes;i++) { | |
val = (val << 8) + ar[i]; | |
} | |
if (val < maxNum - maxNum % range) { | |
return min + (val % range); | |
} | |
} | |
} | |
function makeGames (length) { | |
return new Array(length).fill(0).map(() => { | |
const carDoor = randomInt(0, 3) | |
const playerChoice = randomInt(0, 3) | |
const hostChoices = [0,1,2].filter(door => { | |
if (door === carDoor) return false | |
if (door === playerChoice) return false | |
return true | |
}) | |
const hostChoiceIndex = randomInt(0, hostChoices.length) | |
const hostChoice = hostChoices[hostChoiceIndex] | |
const noSwapWin = carDoor === playerChoice | |
const remainingDoors = [0,1,2].filter(door => door !== hostChoice) | |
const swapDoor = remainingDoors.filter(door => door !== playerChoice)[0] | |
const swapWin = carDoor === swapDoor | |
const randomSwap = randomInt(0, 2) | |
const randomSwapWin = randomSwap ? noSwapWin : swapWin | |
const game = { | |
carDoor, | |
playerChoice, | |
hostChoice, | |
noSwapWin, | |
swapWin, | |
randomSwapWin | |
} | |
return game | |
}) | |
} | |
const totalGames = 50000 | |
const games = makeGames(totalGames) | |
// console.log(games) | |
const stats = games.reduce((previous, current) => { | |
if (current.swapWin) previous.swapWins++ | |
if (current.noSwapWin) previous.noSwapWins++ | |
if (current.randomSwapWin) previous.randomSwapWins++ | |
return previous | |
}, { | |
swapWins: 0, | |
noSwapWins: 0, | |
randomSwapWins: 0 | |
}) | |
stats.totalGames = totalGames | |
stats.swapWinsPercentage = `${(stats.swapWins / totalGames) * 100}%` | |
stats.noSwapWinsPercentage = `${(stats.noSwapWins / totalGames) * 100}%` | |
stats.randomSwapWinsPercentage = `${(stats.randomSwapWins / totalGames) * 100}%` | |
console.log(stats) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment