JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/mathjs/3.4.1/math.min.js"></script>
TypeScript
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
function runExperiment() {
var prisoners = Array.apply(null, { length: 100 })
.map((_, i) => <any>{ index: i, name: `Prisoner ${i+1}` });
var boxes = shuffleArray(prisoners.slice());
var success = prisoners.reduce((success, prisoner) => {
if (!success) return false;
//console.log(`${prisoner.name} is entering the room:`);
var tryCount = 50;
var boxIndex = prisoner.index;
while (tryCount > 0) {
var found = boxes[boxIndex];
if (found == prisoner) {
console.log(`${prisoner.name} found his name at the ${tryCount}th attempt`);
return true;
}
boxIndex = found.index;
tryCount--;
}
console.log(`${prisoner.name} did not find his name, everyone will be executed...`);
return false;
}, true);
if (success) {
console.log('All prisoners found their name, the experiment is a success!!!');
}
return success;
};
runExperiment();