Published
Edited
Dec 12, 2020
1 fork
1 star
Insert cell
Insert cell
program = input.trim().split('\n').map(line => {
const [ op, arg ] = line.split(' ')
return { op, arg: +arg }
})
Insert cell
part1 = run(program)
Insert cell
function* modify(program, op) {
let nextOp = program.findIndex(d => d.op === op)
while (nextOp !== -1) {
const modified = program.slice()
modified[nextOp] = { ...program[nextOp], op: op === 'jmp' ? 'nop' : 'jmp' }
yield modified
nextOp = program.findIndex((d, i) => i > nextOp && d.op === op)
}
}
Insert cell
part2 = {
for (const modified of modify(program, 'jmp')) {
const results = [...run(modified)]
const last = results[results.length - 1]
if (last.length < 3)
return last[1]
}
}
Insert cell
function* run(program) {
const seen = new Set()
let accumulator = 0;
let i = 0;
while (!seen.has(i) && i < program.length) {
seen.add(i)
yield [i, accumulator]
const {op, arg} = program[i]
switch (op) {
case 'acc':
accumulator += arg
break
case 'jmp':
i += arg - 1
break
case 'nop':
default:
break;
}
i++
}
if (i >= program.length)
yield [i, accumulator]
if (seen.has(i))
yield [i, accumulator, 'loop']
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more