Determine the value of the accumulator just before a loop is detected.
const instructions = input
.split('\n')
.map((instruction) => instruction.split(' '))
.map(([operation, arg]) => [operation, +arg])
function visit(index) {
if (visitedIndexes.includes(index)) {
return accumulator
}
visitedIndexes.push(index)
const [operation, arg] = instructions[index]
if (operation === 'acc') {
accumulator += arg
return visit(index + 1)
}
if (operation === 'jmp') {
return visit(index + arg)
}
if (operation === 'nop') {
return visit(index + 1)
}
throw new Error('Unknown operation: ' + operation)
}
let accumulator = 0
const visitedIndexes = []
console.log(visit(0))
Change exactly one
jmp
tonop
or onenop
tojmp
until the program terminates correctly. Then determine the value of the accumulator.
const getInstructions = () =>
input
.split('\n')
.map((instruction) => instruction.split(' '))
.map(([operation, arg]) => [operation, +arg])
function visit(index) {
if (visitedIndexes.includes(index)) {
console.log('Loop detected')
return undefined
}
if (index < 0 || index > instructions.length) {
console.log('Out of bounds')
return undefined
}
if (index === instructions.length) {
console.log('Terminated successfully')
return accumulator
}
visitedIndexes.push(index)
const [operation, arg] = instructions[index]
if (operation === 'acc') {
accumulator += arg
return visit(index + 1)
}
if (operation === 'jmp') {
return visit(index + arg)
}
if (operation === 'nop') {
return visit(index + 1)
}
throw new Error('Unknown operation: ' + operation)
}
let accumulator = 0
let changeIndex = -1
let instructions
let result
let visitedIndexes = []
while (result === undefined) {
accumulator = 0
instructions = getInstructions()
visitedIndexes = []
changeIndex = instructions.findIndex(
([operation], i) => i > changeIndex && ['jmp', 'nop'].includes(operation)
)
instructions[changeIndex][0] =
instructions[changeIndex][0] === 'jmp' ? 'nop' : 'jmp'
result = visit(0)
}
console.log(result)
Quick and dirty with many mutable variables, but gets the job done.
Nothing.