-
Notifications
You must be signed in to change notification settings - Fork 0
/
b.ts
83 lines (66 loc) · 1.76 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
82
83
import { assertEquals } from "https://deno.land/std@0.167.0/testing/asserts.ts";
type Data = number | Data[];
const makeArray = (x: Data) => {
return typeof x === "number" ? [x] : x;
};
const compare = (left: Data, right: Data): -1 | 0 | 1 => {
if (typeof left === "number" && typeof right === "number") {
if (left > right) {
return 1;
}
if (left < right) {
return -1;
}
return 0;
}
if (Array.isArray(left) && Array.isArray(right)) {
for (let i = 0; i < left.length && i < right.length; i++) {
const c = compare(left[i], right[i]);
if (c !== 0) {
return c;
}
}
if (left.length > right.length) {
return 1;
}
if (left.length < right.length) {
return -1;
}
return 0;
}
return compare(makeArray(left), makeArray(right));
};
function solution(input: string) {
const pairs = input
.split("\n\n")
.map((pairsStr) =>
pairsStr.split("\n").map((list) => JSON.parse(list)) as [Data, Data]
);
const flatted = pairs.flat(1).concat([[[2]], [[6]]]);
flatted.sort(compare);
let decoderKey = 1;
flatted.forEach((item, index) => {
if (
Array.isArray(item) &&
item.length === 1 &&
Array.isArray(item[0]) &&
item[0].length === 1 &&
(item[0][0] === 2 || item[0][0] === 6)
) {
decoderKey *= index + 1;
}
});
return decoderKey;
}
Deno.test("example", () => {
const input = Deno.readTextFileSync("./13/example.txt");
const actual = solution(input);
const expected = 140;
assertEquals(actual, expected);
});
Deno.test("puzzle input", { ignore: false }, () => {
const input = Deno.readTextFileSync("./13/input.txt");
const actual = solution(input);
const expected = 19570;
assertEquals(actual, expected);
});