-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpart-one.js
62 lines (51 loc) · 1.39 KB
/
part-one.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
const { input } = require('./input');
function compare(left, right, depth = 0) {
// Loop the upper bounds of left and right
for (let i = 0; i < Math.max(left.length, right.length); i++) {
let li = left[i];
let ri = right[i];
// Out of bounds checks
if (li === undefined) {
return true;
} else if (ri === undefined) {
return false;
}
if (typeof li === 'number' && typeof ri === 'number') {
if (li < ri) {
return true;
} else if (li > ri) {
return false;
} else {
// Same num, continue checking next val
continue;
}
}
// Recursion!
if (Array.isArray(li) && Array.isArray(ri)) {
let substep = compare(li, ri, depth + 1);
// A null result means to pop out of our recursive step onto the next item
if (substep !== null) {
return substep;
}
}
if (Array.isArray(li) && !Array.isArray(ri)) {
return compare(li, [ri], depth + 1);
}
if (!Array.isArray(li) && Array.isArray(ri)) {
return compare([li], ri, depth + 1);
}
}
// This (sub)list was neither right nor wrong
return null;
}
let correct = [];
for (let i = 0; i < input.length; i++) {
let [left, right] = input[i];
let result = compare(left, right);
if (result === true) {
correct.push(i + 1);
} else if (result === null) {
throw new Error(`Failed to compare:\n${JSON.stringify(left)}\n${JSON.stringify(right)}`);
}
}
console.log(correct.reduce((a, b) => a + b, 0));