Day 8 of 2020 done in Python
Single threaded brute force for finding the correct fix. Don't really like it : might be something smarter to do, will try threads.
This commit is contained in:
parent
435fe19dcc
commit
6aca049908
2 changed files with 698 additions and 0 deletions
62
2020/Day 8/Solution.py
Normal file
62
2020/Day 8/Solution.py
Normal file
|
@ -0,0 +1,62 @@
|
|||
input_file = "input.txt"
|
||||
|
||||
|
||||
def run_file(current_line=0, explored_lines=None, accumulator=0, switch=False):
|
||||
"""
|
||||
Run the program contained in the eponymous list. If switch is True, try and correct the program
|
||||
to be able to complete it. Otherwise, exit on program end or repeated instruction.
|
||||
:param current_line: Position to start at in the program (Program Counter)
|
||||
:param explored_lines: Array of already executed instructions, to detect repeats
|
||||
:param accumulator: Starting value of the accumulator
|
||||
:param switch: If True, try to switch a nop to a jmp or vice-versa to fix the program
|
||||
:return: True if booted successfully or if a correction allowed to boot.
|
||||
"""
|
||||
if explored_lines is None:
|
||||
explored_lines = list()
|
||||
|
||||
while current_line <= len(program) - 1:
|
||||
if current_line in explored_lines:
|
||||
print(f"Instruciton at line {current_line} would have been executed twice.\n"
|
||||
f"The accumulator value at this point was {accumulator}")
|
||||
return False
|
||||
|
||||
instruction, argument = program[current_line].split(" ")
|
||||
explored_lines.append(current_line)
|
||||
|
||||
if instruction == "jmp":
|
||||
if switch:
|
||||
# Simulate nop by copying the current state and adding one the the current_line
|
||||
if run_file(current_line+1, explored_lines.copy(), accumulator):
|
||||
print(f"Successful modification at line {current_line}")
|
||||
return True
|
||||
|
||||
current_line += int(argument)
|
||||
|
||||
elif instruction == "nop":
|
||||
if switch:
|
||||
# Simulate a jump by copying the current state but adding the current argument to the current_line
|
||||
if run_file(current_line+int(argument), explored_lines.copy(), accumulator):
|
||||
print(f"Successful modification at line {current_line}")
|
||||
return True
|
||||
|
||||
current_line += 1
|
||||
|
||||
elif instruction == "acc":
|
||||
accumulator += int(argument)
|
||||
current_line += 1
|
||||
|
||||
print(f"Booted successfully !\nThe final accumulator value was {accumulator}")
|
||||
return True
|
||||
|
||||
|
||||
program = []
|
||||
|
||||
|
||||
with open(input_file) as instructions:
|
||||
line = instructions.readline()
|
||||
while line and line != "\n":
|
||||
line = line.strip("\n")
|
||||
program.append(line)
|
||||
line = instructions.readline()
|
||||
|
||||
run_file(switch=True)
|
Loading…
Add table
Add a link
Reference in a new issue