aboutsummaryrefslogtreecommitdiff
path: root/2020/08/solve.js
diff options
context:
space:
mode:
authorMarvin Borner2020-12-08 20:56:10 +0100
committerMarvin Borner2020-12-08 20:56:29 +0100
commita48df2144386d4779aaa73fcaaa46bcc66c79c4d (patch)
treecf5fbac2c35ee6939b750e8a9bc36d17c065b7bc /2020/08/solve.js
parentc3071578cfe3f97cfda05372ff2da64474a9d0c1 (diff)
Fixed naming for 10+ challenges
Diffstat (limited to '2020/08/solve.js')
-rw-r--r--2020/08/solve.js52
1 files changed, 52 insertions, 0 deletions
diff --git a/2020/08/solve.js b/2020/08/solve.js
new file mode 100644
index 0000000..c03edcb
--- /dev/null
+++ b/2020/08/solve.js
@@ -0,0 +1,52 @@
+const fs = require("fs");
+const data = fs.readFileSync("input", "utf8").split('\n');
+
+function run(code)
+{
+ let acc = 0;
+ let visited = [];
+
+ let i = 0;
+ while (!visited.includes(i)) {
+ visited.push(i);
+ if (!code[i])
+ return { acc, i };
+
+ const [op, cnt] = code[i].split(" ");;
+ switch (op) {
+ case "acc":
+ acc += +cnt;
+ break;
+ case "jmp":
+ i += +cnt - 1;
+ break;
+ default:
+ break;
+ }
+ i++;
+ }
+ return { acc, i };
+}
+
+function partOne()
+{
+ return run(data).acc;
+}
+
+function partTwo()
+{
+ for (let i = 0; i < data.length; i++) {
+ const [op, cnt] = data[i].split(" ");;
+ if (op == "acc")
+ continue; // Skip correction
+
+ let fixed = [...data];
+ fixed.splice(i, 1, `${op == "nop" ? "jmp" : "nop"} ${cnt}`);
+ let results = run(fixed);
+ if (results.i == fixed.length)
+ return results.acc;
+ }
+}
+
+console.log(partOne());
+console.log(partTwo());