Last active
August 25, 2022 06:33
-
-
Save x0a/8263efe17212c8a62ba09836caf46c89 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 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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Context https://www.youtube.com/watch?v=iSNsgj1OCLA