DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 8: Handheld Halting

Collapse
 
kudostoy0u profile image
Kudos Beluga • Edited

Here's a javascript solution. Toggle part2 to false or true depending on what part you're on.

let fs = require("fs"), acc = 0, taken = [],part2=true;
const check = (data,index,returnfunc=()=>{}) => {
if (taken.indexOf(index) > -1) returnfunc(acc)
  else {
  taken.push(index)
  let dedata = data[index]
  if (!dedata) console.log(acc)
  else {
  switch (dedata.slice(0,3)) {
    case "nop": check(data,index+1,returnfunc)
    break;
    case "acc": acc = acc + Number(dedata.match(/(?<=.{3} ).+/i)[0])
     check(data,index+1,returnfunc)
    break;
    case "jmp": check(data,index+Number(dedata.match(/(?<=.{3} ).+/i)[0]),returnfunc)
    break;
  }}}}
  const controller = data => {
  const returnfunc = val => {if (!part2) console.log(val)}
  if (part2) {
   for (let i in data) {
     let modifieddata = [...data];
     if ((data[i].slice(0,3) != "acc")) {
    if (data[i].slice(0,3) == "nop") modifieddata[i] = "jmp " + data[i].slice(4,data[i].length) 
    else modifieddata[i] = "nop " + data[i].slice(4,data[i].length) 
    taken = [], acc = 0, check(modifieddata,0) 
     }}} else check(data,0,returnfunc) }
fs.readFile("input.txt","utf8", (err,data) => controller(data.split("\n")))
Enter fullscreen mode Exit fullscreen mode