Skip to content

Instantly share code, notes, and snippets.

@halitanildonmez
Created December 17, 2020 17:32
Show Gist options
  • Save halitanildonmez/5019e0f3d163dc40c6c7156340d2f648 to your computer and use it in GitHub Desktop.
Save halitanildonmez/5019e0f3d163dc40c6c7156340d2f648 to your computer and use it in GitHub Desktop.
The solutions for day 8 of Advent of Code 2020
def advent_day_8_pt2_solver(instructions):
N = len(instructions)
index = 0
acc = 0
visited = []
candidates = []
while index < N:
if index in visited:
return acc, candidates, False
ins = instructions[index]
sp = ins.split(' ')
if len(sp) == 1:
continue
command = sp[0]
command_val = int(sp[1])
if command == 'nop':
visited.append(index)
candidates.append(index)
index += 1
continue
if command == 'acc':
visited.append(index)
index += 1
acc += command_val
continue
# jump
visited.append(index)
candidates.append(index)
index += command_val
return acc, candidates, True
def advent_day_8_pt2():
instructions = []
instructions_orig = []
with open('input.txt', 'r') as file:
lst = file.read().split('\n')
instructions = lst
instructions_orig = instructions
instructions.pop()
res = advent_day_8_pt2_solver(instructions)
if res[2] == False:
inst = instructions
for ch_index in res[1]:
old_instruction = inst[ch_index]
new_instruction = ""
if "jmp" in old_instruction:
new_instruction = old_instruction.replace("jmp", "nop")
else:
new_instruction = old_instruction.replace("nop", "jmp")
inst[ch_index] = new_instruction
g = advent_day_8_pt2_solver(inst)
if g[2] == True:
print('suc ', g)
break
else:
inst[ch_index] = old_instruction
print('done')
if __name__ == '__main__':
advent_day_8_pt2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment