Refactoring
This commit is contained in:
parent
49d870233a
commit
e2a5cee90e
32
src/P8.py
32
src/P8.py
@ -74,34 +74,34 @@ with open("files/P8.txt", "r") as f:
|
||||
|
||||
|
||||
def part_1(lines: List[str], debug: bool = False) -> Tuple[int, bool]:
|
||||
acc = 0
|
||||
accu = 0
|
||||
executed = []
|
||||
nline = 0
|
||||
while True:
|
||||
try:
|
||||
instr = lines[nline]
|
||||
instr, acc = lines[nline].split(" ")
|
||||
if nline in executed:
|
||||
# we are in a for loop :(
|
||||
break
|
||||
else:
|
||||
executed.append(nline)
|
||||
if instr[:3] == "acc":
|
||||
acc += int(instr[4:])
|
||||
if instr == "acc":
|
||||
accu += int(acc)
|
||||
nline += 1
|
||||
continue
|
||||
elif instr[:3] == "jmp":
|
||||
nline = nline + int(instr[4:])
|
||||
elif instr == "jmp":
|
||||
nline = nline + int(acc)
|
||||
continue
|
||||
elif instr[:3] == "nop":
|
||||
elif instr == "nop":
|
||||
nline += 1
|
||||
continue
|
||||
except IndexError:
|
||||
if debug:
|
||||
print("Code has run successfully")
|
||||
return acc, True
|
||||
return accu, True
|
||||
if debug:
|
||||
print(f"The value of the accumulator was {acc} before exiting")
|
||||
return acc, False
|
||||
print(f"The value of the accumulator was {accu} before exiting")
|
||||
return accu, False
|
||||
|
||||
|
||||
# --- Part Two ---
|
||||
@ -159,20 +159,20 @@ def part_1(lines: List[str], debug: bool = False) -> Tuple[int, bool]:
|
||||
|
||||
def part_2() -> None:
|
||||
for nline, _ in enumerate(lines):
|
||||
inst = lines[nline]
|
||||
inst, acc = lines[nline].split(" ")
|
||||
# change instructions
|
||||
if inst[:3] == "nop":
|
||||
if inst == "nop":
|
||||
new_inst = "jmp"
|
||||
elif inst[:3] == "jmp":
|
||||
elif inst == "jmp":
|
||||
new_inst = "nop"
|
||||
|
||||
# make a copy of the original code
|
||||
new_lines = lines.copy()
|
||||
# change line according to the instructions in the original code
|
||||
new_lines[nline] = " ".join((new_inst, inst[4:]))
|
||||
acc, has_ended = part_1(new_lines)
|
||||
new_lines[nline] = " ".join((new_inst, acc))
|
||||
accu, has_ended = part_1(new_lines)
|
||||
if has_ended:
|
||||
print(f"The value of the accumulator was {acc} after terminates")
|
||||
print(f"The value of the accumulator was {accu} after terminates")
|
||||
break
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user