Skip to content

Latest commit

 

History

History
121 lines (94 loc) · 8.22 KB

08.md

File metadata and controls

121 lines (94 loc) · 8.22 KB

Day 08

Part 1

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))

Try it out on flems.io

Part 2

Change exactly one jmp to nop or one nop to jmp 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)

flems

Quick and dirty with many mutable variables, but gets the job done.

What did I learn?

Nothing.