Skip to content

Instantly share code, notes, and snippets.

@redspider
Created December 8, 2020 07:33
Show Gist options
  • Save redspider/101e79c32a28f7a9af7399df2b453080 to your computer and use it in GitHub Desktop.
Save redspider/101e79c32a28f7a9af7399df2b453080 to your computer and use it in GitHub Desktop.
def run_program(program):
acc = 0
pointer = 0
seen = set()
while pointer not in seen:
op, value = program[pointer]
seen.add(pointer)
if op == 'nop':
pointer += 1
if op == 'acc':
acc += value
pointer += 1
if op == 'jmp':
pointer += value
if op == 'ext':
return True, acc
return False, acc
program = [(op, int(value)) for op, value in [line.split(" ") for line in INPUT.split("\n")]]
program.append(('ext', 0))
# Part 1:
success, acc = run_program(program)
print(acc)
# Part 2:
for offset, (op, value) in enumerate(program):
if op in ['jmp', 'nop']:
program[offset] = ('nop' if op == 'jmp' else 'jmp', value)
success, acc = run_program(program)
if success:
print(acc)
break
program[offset] = (op, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment