Created
December 8, 2020 14:31
-
-
Save cranderveldt/46ec5118b44bd86be93fc45c037e131b to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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