-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13.js
77 lines (74 loc) · 1.79 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
/**
*
* @param {(number|number[])[]} left
* @param {(number|number[])[]} right
* @returns {number}
*/
function comparePairs(left, right) {
let index = 0;
while (index < left.length && index < right.length) {
if (left[index].constructor === Array && right[index].constructor === Array) {
const ret = comparePairs(left[index], right[index]);
if (ret !== 0) {
return ret;
}
}
else if (left[index].constructor === Array) {
// Need to double check this
const ret = comparePairs(left[index], [right[index]]);
if (ret !== 0) {
return ret;
}
}
else if (right[index].constructor === Array) {
// Need to double check this
const ret = comparePairs([left[index]], right[index]);
if (ret !== 0) {
return ret;
}
}
else {
if (left[index] < right[index]) {
return -1;
}
if (left[index] > right[index]) {
return 1;
}
}
index++;
}
// Fall through for when one is shorter than the other, but same otherwise
if (index == left.length && index < right.length) {
return -1;
}
if (index < left.length && index == right.length) {
return 1;
}
return 0;
}
/**
* @param {string} d
*/
export const part1 = async d => {
const data = d.split('\n\n').map(e => e.split('\n').map(e => JSON.parse(e)));
const rightOrder = [];
data.forEach((pair, index) => {
if (comparePairs(...pair) == -1) {
rightOrder.push(index + 1);
}
});
return rightOrder.reduce((p, v) => p + v, 0);
};
/**
* @param {string} d
*/
export const part2 = async d => {
const data = (d + '\n[[2]]\n[[6]]').split('\n\n')
.join('\n')
.split('\n')
.map(e => JSON.parse(e))
.sort((a, b) => comparePairs(a, b))
.map(e => JSON.stringify(e));
const decoderPacket = [data.indexOf('[[2]]') + 1, data.indexOf('[[6]]') + 1];
return decoderPacket.reduce((p, v) => p * v, 1);
};