-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
70 lines (59 loc) · 1.42 KB
/
part2.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
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString();
const rules = [];
const updates = [];
input.split("\n").forEach((line) => {
if (line.includes("|")) {
rules.push(line.split("|").map((x) => parseInt(x)));
} else if (line.includes(",")) {
updates.push(line.split(",").map((x) => parseInt(x)));
}
});
function applyRule(rule, update) {
const n1 = update.indexOf(rule[0]);
const n2 = update.indexOf(rule[1]);
if (n1 == -1 || n2 == -1 || n1 < n2) {
return;
}
let newUpdate = update;
let temp = newUpdate[n2];
newUpdate[n2] = newUpdate[n1];
newUpdate[n1] = temp;
return newUpdate;
}
function findRulesForNumber(number) {
const result = [];
rules.forEach((r) => {
if (r.includes(number)) result.push(r);
});
return result;
}
const invalid = [];
updates.forEach((u) => {
let currentUpdate = u;
let updated = false;
let modified = true;
while (modified) {
modified = false;
currentUpdate.forEach((n) => {
findRulesForNumber(n).forEach((r) => {
const fixed = applyRule(r, currentUpdate);
if (fixed) {
currentUpdate = fixed;
updated = true;
modified = true;
}
});
});
}
if (updated) {
invalid.push(currentUpdate);
}
});
let result = 0;
invalid.forEach((u) => {
result += u[(u.length / 2) >> 0];
});
console.log(result);