-
Notifications
You must be signed in to change notification settings - Fork 0
/
b.ts
81 lines (69 loc) · 2.32 KB
/
b.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
73
74
75
76
77
78
79
80
81
import { assertEquals } from "https://deno.land/std@0.167.0/testing/asserts.ts";
type Monkey = {
id: number;
items: number[];
operation: (worry: number) => number;
test: (worry: number) => number;
divisibleBy: number;
};
function solution(input: string) {
const monkeys = input.split("\n\n").map<Monkey>((line) => {
const note = line.split("\n");
return {
id: Number(note[0].split(" ")[1].replace(":", "")),
items: note[1].split(": ")[1].split(", ").map((n) => Number(n)),
operation: (worry) => {
const [op, arg] = note[2].split("new = old ")[1].split(" ");
const parsedArg = arg === "old" ? worry : Number(arg);
if (op === "+") {
return worry + parsedArg;
}
if (op === "*") {
return worry * parsedArg;
}
throw new Error(`Invalid operator: ${op}`);
},
divisibleBy: Number(note[3].split("divisible by ")[1]),
test: (worry) => {
const n = Number(note[3].split("divisible by ")[1]);
const trueResult = Number(note[4].split("throw to monkey ")[1]);
const falseResult = Number(note[5].split("throw to monkey ")[1]);
if (worry % n === 0) {
return trueResult;
} else {
return falseResult;
}
},
};
});
const leaderboard: number[] = Array.from({ length: monkeys.length }, () => 0);
const mod = monkeys.reduce((acc, monkey) => acc * monkey.divisibleBy, 1);
for (let i = 1; i <= 10_000; i++) {
monkeys.forEach((monkey) => {
while (monkey.items.length > 0) {
const worry = monkey.items.shift()!;
const nextWorry = monkey.operation(worry) % mod;
const nextMonkey = monkey.test(nextWorry);
monkeys[nextMonkey].items.push(nextWorry);
leaderboard[monkey.id]++;
}
});
}
const result = leaderboard
.sort((a, b) => b - a)
.slice(0, 2)
.reduce((a, b) => a * b);
return result;
}
Deno.test("example", () => {
const input = Deno.readTextFileSync("./11/example.txt");
const actual = solution(input);
const expected = 2713310158;
assertEquals(actual, expected);
});
Deno.test("puzzle input", { ignore: false }, () => {
const input = Deno.readTextFileSync("./11/input.txt");
const actual = solution(input);
const expected = 25272176808;
assertEquals(actual, expected);
});