Parsing input before execute

This commit is contained in:
Daniel Cortés
2020-12-08 05:57:20 -03:00
parent 57e28cc899
commit 1f8936f6f1

View File

@@ -1,18 +1,27 @@
import timeit import timeit
def execute(memory): def parse_code(data):
acc = 0 #accumulator code = []
ip = 0 #instruction pointer
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() visited = set()
while True: while True:
if ip in visited: return (acc, False) # Acumulator, Ended if ip in visited: return (acc, False)
if ip >= len(memory): return (acc, True) #Acumulator, Ended if ip >= len(code): return (acc, True)
visited.add(ip) visited.add(ip)
instruction, argument = memory[ip].split(' ') instruction, argument = code[ip]
argument = int(argument)
if instruction == 'nop': if instruction == 'nop':
ip += 1 ip += 1
@@ -22,27 +31,23 @@ def execute(memory):
elif instruction == 'jmp': elif instruction == 'jmp':
ip += argument ip += argument
def swap_nop_jmp(memory, ip): def swap_nop_jmp(code, ip):
instruction, argument = memory[ip].split(' ') instruction, argument = code[ip]
if instruction == "nop": memory[ip] = f"jmp {argument}" if instruction == 'nop': code[ip] = ('jmp', argument)
elif instruction == "jmp": memory[ip] = f"nop {argument}" elif instruction == 'jmp': code[ip] = ('nop', argument)
else: memory = [] else: code = []
return memory return code
def solve_a(code):
return execute(code)
def solve_a(memory): def solve_b(og_code):
return execute(memory) for ip in range(len(og_code)):
code = swap_nop_jmp(og_code.copy(), ip)
if not code: continue
def solve_b(memory): result, ended = execute(code)
for ip in range(len(memory)): if ended: return (result, ended)
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"
def time(function): def time(function):
start = timeit.default_timer() start = timeit.default_timer()
@@ -50,10 +55,14 @@ def time(function):
end = timeit.default_timer() end = timeit.default_timer()
return ((end - start) * 1000, result) return ((end - start) * 1000, result)
memory = [line.strip() for line in open('input')]
elapsed, solution = time(lambda: solve_a(memory)) 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}') print(f'Part N°1 [{elapsed:.4f}ms] = {solution}')
elapsed, solution = time(lambda: solve_b(memory)) elapsed, solution = time(lambda: solve_b(code))
print(f'Part N°2 [{elapsed:.4f}ms] = {solution}') print(f'Part N°2 [{elapsed:.4f}ms] = {solution}')