Parsing input before execute
This commit is contained in:
@@ -1,18 +1,27 @@
|
||||
import timeit
|
||||
|
||||
def execute(memory):
|
||||
acc = 0 #accumulator
|
||||
ip = 0 #instruction pointer
|
||||
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) # Acumulator, Ended
|
||||
if ip >= len(memory): return (acc, True) #Acumulator, Ended
|
||||
if ip in visited: return (acc, False)
|
||||
if ip >= len(code): return (acc, True)
|
||||
|
||||
visited.add(ip)
|
||||
|
||||
instruction, argument = memory[ip].split(' ')
|
||||
argument = int(argument)
|
||||
instruction, argument = code[ip]
|
||||
|
||||
if instruction == 'nop':
|
||||
ip += 1
|
||||
@@ -22,27 +31,23 @@ def execute(memory):
|
||||
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 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_a(memory):
|
||||
return execute(memory)
|
||||
def solve_b(og_code):
|
||||
for ip in range(len(og_code)):
|
||||
code = swap_nop_jmp(og_code.copy(), ip)
|
||||
if not code: continue
|
||||
|
||||
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"
|
||||
result, ended = execute(code)
|
||||
if ended: return (result, ended)
|
||||
|
||||
def time(function):
|
||||
start = timeit.default_timer()
|
||||
@@ -50,10 +55,14 @@ def time(function):
|
||||
end = timeit.default_timer()
|
||||
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}')
|
||||
|
||||
elapsed, solution = time(lambda: solve_b(memory))
|
||||
elapsed, solution = time(lambda: solve_b(code))
|
||||
print(f'Part N°2 [{elapsed:.4f}ms] = {solution}')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user