Skip to content

Instantly share code, notes, and snippets.

@bcomnes
Created May 14, 2021 20:36
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 bcomnes/7fe3bde09597ee140d5972a939602845 to your computer and use it in GitHub Desktop.
Save bcomnes/7fe3bde09597ee140d5972a939602845 to your computer and use it in GitHub Desktop.
a monty-hall solution
// 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