day 8 added <3
This commit is contained in:
47
2020/day_8/handheld_halting.py
Normal file
47
2020/day_8/handheld_halting.py
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
def execute(memory):
|
||||||
|
acc = 0 #accumulator
|
||||||
|
ip = 0 #instruction pointer
|
||||||
|
|
||||||
|
visited = set()
|
||||||
|
while True:
|
||||||
|
if ip in visited: return (acc, False) # Acumulator, Ended
|
||||||
|
if ip >= len(memory): return (acc, True) #Acumulator, Ended
|
||||||
|
|
||||||
|
visited.add(ip)
|
||||||
|
|
||||||
|
instruction, argument = memory[ip].split(' ')
|
||||||
|
argument = int(argument)
|
||||||
|
|
||||||
|
if instruction == 'nop':
|
||||||
|
ip += 1
|
||||||
|
elif instruction =='acc':
|
||||||
|
acc += argument
|
||||||
|
ip += 1
|
||||||
|
elif instruction == 'jmp':
|
||||||
|
ip += argument
|
||||||
|
|
||||||
|
def swap_nop_jmp(memory, ip):
|
||||||
|
instruction, argument = memory[ip].split(' ')
|
||||||
|
if instruction == "nop": memory[ip] = f"jmp {argument}"
|
||||||
|
elif instruction == "jmp": memory[ip] = f"nop {argument}"
|
||||||
|
else: memory = []
|
||||||
|
return memory
|
||||||
|
|
||||||
|
|
||||||
|
def solve_a(memory):
|
||||||
|
return execute(memory)
|
||||||
|
|
||||||
|
def solve_b(memory):
|
||||||
|
for ip in range(len(memory)):
|
||||||
|
memory_copy = swap_nop_jmp(memory.copy(), ip)
|
||||||
|
if not memory_copy: continue
|
||||||
|
|
||||||
|
result, ended = execute(memory_copy)
|
||||||
|
if ended:
|
||||||
|
return (result, ended)
|
||||||
|
|
||||||
|
return "OH NO"
|
||||||
|
|
||||||
|
memory = [line.strip() for line in open('input')]
|
||||||
|
print(solve_a(memory))
|
||||||
|
print(solve_b(memory))
|
||||||
Reference in New Issue
Block a user