69 lines
1.5 KiB
Python
69 lines
1.5 KiB
Python
import timeit
|
|
|
|
def parse_code(data):
|
|
code = []
|
|
|
|
for line in data:
|
|
instruction, argument = line.split(' ')
|
|
argument = int(argument)
|
|
code.append((instruction, argument))
|
|
|
|
return code
|
|
|
|
def execute(code):
|
|
acc = 0
|
|
ip = 0
|
|
|
|
visited = set()
|
|
while True:
|
|
if ip in visited: return (acc, False)
|
|
if ip >= len(code): return (acc, True)
|
|
|
|
visited.add(ip)
|
|
|
|
instruction, argument = code[ip]
|
|
|
|
if instruction == 'nop':
|
|
ip += 1
|
|
elif instruction =='acc':
|
|
acc += argument
|
|
ip += 1
|
|
elif instruction == 'jmp':
|
|
ip += argument
|
|
|
|
def swap_nop_jmp(code, ip):
|
|
instruction, argument = code[ip]
|
|
if instruction == 'nop': code[ip] = ('jmp', argument)
|
|
elif instruction == 'jmp': code[ip] = ('nop', argument)
|
|
else: code = []
|
|
return code
|
|
|
|
def solve_a(code):
|
|
return execute(code)
|
|
|
|
def solve_b(og_code):
|
|
for ip in range(len(og_code)):
|
|
code = swap_nop_jmp(og_code.copy(), ip)
|
|
if not code: continue
|
|
|
|
result, ended = execute(code)
|
|
if ended: return (result, ended)
|
|
|
|
def time(function):
|
|
start = timeit.default_timer()
|
|
result = function()
|
|
end = timeit.default_timer()
|
|
return ((end - start) * 1000, result)
|
|
|
|
|
|
data = [line.strip() for line in open('input')]
|
|
code = parse_code(data)
|
|
|
|
elapsed, solution = time(lambda: solve_a(code))
|
|
print(f'Part N°1 [{elapsed:.4f}ms] = {solution}')
|
|
|
|
elapsed, solution = time(lambda: solve_b(code))
|
|
print(f'Part N°2 [{elapsed:.4f}ms] = {solution}')
|
|
|
|
|