-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8_final.js
78 lines (68 loc) · 1.9 KB
/
day8_final.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
exports.__esModule = true;
var lines = require("./day8Data");
const fs = require("fs");
class Program {
constructor(string, options = {}) {
this.accumulator = 0;
this.pointer = 0;
this.done = new Set();
this.options = options;
this.isFinished = false;
this.code = string
.split("\n")
.filter((x) => x)
.map((line) => {
const { groups } = /^(?<instruction>\D+) \+?(?<value>-?\d+)$/.exec(
line
);
groups.value = parseInt(groups.value);
return groups;
});
}
run() {
while (true) {
if (this.pointer == this.code.length) {
this.isFinished = true;
break;
}
const { instruction, value } = this.code[this.pointer];
if (this.done.has(this.pointer)) {
if (this.options.infiniteLoopWarning)
console.log("INFINITE LOOP", { accumulator: this.accumulator });
break;
}
this.done.add(this.pointer);
switch (instruction) {
case "nop":
this.pointer++;
break;
case "acc":
this.accumulator += value;
this.pointer++;
break;
case "jmp":
this.pointer += value;
break;
default:
throw new Error("not implemented");
break;
}
}
}
}
const p = new Program(lines.textInput, { infiniteLoopWarning: true });
p.run();
const code = p.code;
for (let i = 0; i < code.length; i++) {
const element = code[i];
if (element.instruction === "nop" || element.instruction === "jmp") {
const copy = JSON.parse(JSON.stringify(code));
copy[i].instruction = element.instruction === "nop" ? "jmp" : "nop";
const newSource = copy.map((x) => `${x.instruction} ${x.value}`).join("\n");
const fixedProgram = new Program(newSource);
fixedProgram.run();
if (fixedProgram.isFinished) {
console.log(fixedProgram.accumulator);
}
}
}