-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpart-two.js
105 lines (90 loc) · 2.09 KB
/
part-two.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const { input } = require('./input');
const divider2 = [[2]];
const divider6 = [[6]];
// Turn this on to see logs
const debug = false;
// prettier-ignore
const input_all = [
...input.flat(),
divider2,
divider6,
];
function compare(left, right, depth = 0, debug = false) {
if (depth === 0 && debug) {
console.log('========');
}
for (let i = 0; i < Math.max(left.length, right.length); i++) {
let li = left[i];
let ri = right[i];
if (debug) {
console.log(
'Compare'.padStart(7 + depth * 2),
JSON.stringify(li),
'vs',
JSON.stringify(ri)
);
}
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;
}
}
if (Array.isArray(li) && Array.isArray(ri)) {
let substep = compare(li, ri, depth + 1, debug);
if (substep !== null) {
return substep;
}
} else if (Array.isArray(li) && !Array.isArray(ri)) {
if (debug) {
console.log(
' '.repeat(depth * 2) +
`Mixed types; convert right to [${ri}] and retry comparison`
);
}
let substep = compare(li, [ri], depth + 1, debug);
if (substep !== null) {
return substep;
}
} else if (!Array.isArray(li) && Array.isArray(ri)) {
if (debug) {
console.log(
' '.repeat(depth * 2) +
`Mixed types; convert left to [${li}] and retry comparison`
);
}
let substep = compare([li], ri, depth + 1, debug);
if (substep !== null) {
return substep;
}
}
}
// This (sub)list was neither right nor wrong
return null;
}
input_all.sort((a, b) => {
const comparison = compare(a, b, undefined, debug);
if (comparison === true) {
return -1;
} else if (comparison === false) {
return 1;
} else {
return 0;
}
});
if (debug) {
console.log('Sorted list:');
input_all.forEach((l) => console.log(JSON.stringify(l)));
}
let a = input_all.indexOf(divider2);
let b = input_all.indexOf(divider6);
console.log((a + 1) * (b + 1));