Skip to content

Instantly share code, notes, and snippets.

@cranderveldt
Created December 8, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cranderveldt/46ec5118b44bd86be93fc45c037e131b to your computer and use it in GitHub Desktop.
Save cranderveldt/46ec5118b44bd86be93fc45c037e131b to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 8
const puzzleInput = ``
// Part 1
const parseInput = (input) => {
return input.split(/\n/)
}
const interpretInstruction = (line) => {
let [command, amount] = line.split(' ')
return {
amount: parseInt(amount),
command,
}
}
const runInstructions = (acc, instructions, index) => {
const instruction = instructions[index]
if (acc[index] || !instruction) { return { count: acc.count, loop: acc[index] } }
acc[index] = true
switch (instruction.command) {
case 'jmp': return runInstructions(acc, instructions, index + instruction.amount)
case 'acc': acc.count += instruction.amount
default: return runInstructions(acc, instructions, index + 1)
}
}
const partOne = (input) => {
const instructions = parseInput(input).map(interpretInstruction)
const result = runInstructions({ count: 0 }, instructions, 0)
console.log(result.count)
}
partOne(puzzleInput)
// Part 2
const autoFixProgram = (instructions) => {
return instructions.reduce((acc, instruction, index) => {
if (!!acc || instruction.command === 'acc') { return acc }
instruction.command = instruction.command === 'jmp' ? 'nop' : 'jmp'
const result = runInstructions({ count: 0 }, instructions, 0)
instruction.command = instruction.command === 'jmp' ? 'nop' : 'jmp'
return result.loop ? acc : { count: result.count, index }
}, null)
}
const partTwo = (input) => {
const instructions = parseInput(input).map(interpretInstruction)
const result = autoFixProgram(instructions)
console.log(result && result.count)
}
partTwo(puzzleInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment