From a48df2144386d4779aaa73fcaaa46bcc66c79c4d Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Tue, 8 Dec 2020 20:56:10 +0100 Subject: Fixed naming for 10+ challenges --- 2020/08/solve.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 2020/08/solve.js (limited to '2020/08/solve.js') 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()); -- cgit v1.2.3