-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.js
87 lines (70 loc) · 1.7 KB
/
13.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const isTesting = false;
const input = isTesting
? `[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]`
: ``;
const isCorrectOrder = (left, right) => {
if (!Array.isArray(left) && !Array.isArray(right)) {
if (left < right) return 1;
if (left > right) return -1;
return null;
}
// Force arrays
const leftArray = Array.isArray(left) ? left : [left];
const rightArray = Array.isArray(right) ? right : [right];
for (let i = 0; i < Math.min(leftArray.length, rightArray.length); i++) {
const isCorrect = isCorrectOrder(leftArray[i], rightArray[i]);
if (isCorrect !== null) {
return isCorrect;
}
}
if (leftArray.length < rightArray.length) return 1;
if (leftArray.length > rightArray.length) return -1;
return null; // unknown, continue to the next one
};
const partOne = () => {
const rows = input.split("\n");
const pairs = [];
for (let i = 0; i < rows.length; i += 3) {
pairs.push({ left: eval(rows[i]), right: eval(rows[i + 1]) });
}
console.log(
"Part 1",
pairs
.map(({ left, right }, i) =>
isCorrectOrder(left, right) === 1 ? i + 1 : 0
)
.filter((v) => v != 0)
.reduce((s, v) => s + v)
);
};
partOne();
const partTwo = () => {
const rows = input
.split("\n")
.filter((r) => r.length > 0)
.map(eval);
const dividerA = [[2]];
const dividerB = [[6]];
rows.push(dividerA, dividerB);
const sortedRows = rows.sort(isCorrectOrder).reverse();
console.log(
"Part 2",
(sortedRows.indexOf(dividerA) + 1) * (sortedRows.indexOf(dividerB) + 1)
);
};
partTwo();