-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop.js
66 lines (54 loc) · 1.87 KB
/
loop.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function simulatePrisoners(strategy) {
const numPrisoners = 100;
const numBoxes = 100;
const numSimulations = 1000;
const numTries = 50;
let successCount = 0;
for (let sim = 0; sim < numSimulations; sim++) {
let boxes = Array.from({ length: numBoxes }, (_, i) => i + 1);
let slips = boxes.slice();
for (let i = slips.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[slips[i], slips[j]] = [slips[j], slips[i]];
}
let allPrisonersSucceeded = true;
for (let prisoner = 1; prisoner <= numPrisoners; prisoner++) {
let found = false;
let openedBoxes = new Set();
let currentBox;
if (strategy) {
currentBox = prisoner;
} else {
currentBox = Math.floor(Math.random() * numBoxes) + 1;
}
for (let tries = 0; tries < numTries; tries++) {
if (openedBoxes.has(currentBox)) {
break;
}
openedBoxes.add(currentBox);
if (slips[currentBox - 1] === prisoner) {
found = true;
break;
}
if (strategy) {
currentBox = slips[currentBox - 1];
} else {
do {
currentBox = Math.floor(Math.random() * numBoxes) + 1;
} while (openedBoxes.has(currentBox));
}
}
if (!found) {
allPrisonersSucceeded = false;
break;
}
}
if (allPrisonersSucceeded) {
successCount++;
}
}
return successCount;
}
const strategy = false;
const result = simulatePrisoners(strategy);
console.log(`Number of successful simulations: ${result}`);