Skip to content

Instantly share code, notes, and snippets.

@x0a
Last active August 25, 2022 06:33
Show Gist options
  • Save x0a/8263efe17212c8a62ba09836caf46c89 to your computer and use it in GitHub Desktop.
Save x0a/8263efe17212c8a62ba09836caf46c89 to your computer and use it in GitHub Desktop.
const getRandomizedBoxes = ()=>{
const getRandomInt = (min,max)=>{
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
//The maximum is exclusive and the minimum is inclusive
}
const boxes = Array(100);
for (let i = 0; i < 100; i++) {
let randInt;
do {
const randInt = getRandomInt(0, 100);
if (boxes.indexOf(randInt) === -1)
boxes[i] = randInt;
} while (typeof boxes[i] !== 'number')
}
return boxes;
}
const runSimulation = ()=>{
let solved = 0;
const boxes = getRandomizedBoxes();
for (let prisoner = 0; prisoner < 100; prisoner++) {
let boxIndex = prisoner;
for (let i = 0; i < 50; i++) {
if (boxes[boxIndex] === prisoner) {
solved++
break;
} else {
boxIndex = boxes[boxIndex]
}
}
}
return solved;
}
let successful = 0;
for (let i = 0; i < 100000; i++) {
successful += runSimulation() === 100 ? 1 : 0;
}
const ratio = successful / 100000;
console.log('Prisoners were freed on average', (ratio * 100) + '%', 'of the time')
@x0a
Copy link
Author

x0a commented Jul 3, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment