-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
72 lines (61 loc) · 1.92 KB
/
mod.ts
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
67
68
69
70
71
72
const makeNumArray = (num: number) => {
const arr: number[] = [];
for (let i = 1; i <= num; i++) arr.push(i);
return arr;
};
// deno-lint-ignore no-explicit-any
export const getRandomIndex = (arr: any[]) =>
Math.floor(Math.random() * arr.length);
export interface Drawer {
drawerNumber: number;
prisonerNumber: number;
}
export const createDrawers = (num: number) => {
const prisoners = makeNumArray(num);
const drawers: Drawer[] = [];
for (let i = 1; i <= num; i++) {
const idx = getRandomIndex(prisoners);
const prisonerNumber = prisoners[idx];
drawers.push({ drawerNumber: i, prisonerNumber });
prisoners.splice(idx, 1);
}
return drawers;
};
export const runSimulation = (
strategy: (drawers: readonly Drawer[], prisonerNumber: number) => Drawer[],
numberOfSimulations = 1,
numberOfPrisoners = 100
) => {
let fails = 0;
for (let i = 0; i < numberOfSimulations; i++) {
const drawers = createDrawers(numberOfPrisoners);
Object.freeze(drawers);
for (let j = 1; j <= numberOfPrisoners; j++) {
const halfTheDrawers = strategy(drawers, j);
if (!Array.isArray(halfTheDrawers))
throw new Error("Strategy must return an array");
const didOpenLessThanHalf =
halfTheDrawers.length <= numberOfPrisoners / 2;
if (!didOpenLessThanHalf)
throw new Error(`Prisoner ${j} opened more than half the drawers`);
const areValidDrawers = halfTheDrawers.every((b) => drawers.includes(b));
if (!areValidDrawers)
throw new Error(
`Prisoner ${j} opened invalid drawers ${halfTheDrawers}`
);
// if one prisoner fails, the whole simulation fails
const isCorrectNumber = halfTheDrawers.some(
(b) => b.prisonerNumber === j
);
if (!isCorrectNumber) {
fails++;
break;
}
}
}
return {
fails,
passes: numberOfSimulations - fails,
total: numberOfSimulations,
};
};