109 lines
2.9 KiB
Python
109 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
file = "./input.txt"
|
|
ex1 = ["R2", "L3"]
|
|
ex2 = ["R2", "R2", "R2"]
|
|
ex3 = ["R5", "L5", "R5", "R3"]
|
|
ex4 = ["R8", "R4", "R4", "R8"]
|
|
|
|
from time import time
|
|
start_time = time()
|
|
|
|
def read_file(f:str) -> list:
|
|
out = []
|
|
input_file = open(f, "r")
|
|
for line in input_file:
|
|
line = line.strip()
|
|
if line == "":
|
|
continue
|
|
else:
|
|
line = line.replace(" ","").split(',')
|
|
out.extend(line)
|
|
input_file.close()
|
|
return out
|
|
|
|
def check_position(pos:tuple[int, int]):
|
|
if pos in pos_list:
|
|
print(f'Solution P2: {abs(pos[0]) + abs(pos[1])}')
|
|
global part2
|
|
part2 = False
|
|
else:
|
|
pos_list.append(pos)
|
|
|
|
|
|
def go(pos:tuple[int, int, str], steps:str) -> tuple[int, int, str]:
|
|
global part2
|
|
we, ns, direction = pos
|
|
step = int(steps[1:])
|
|
if direction == "N":
|
|
if steps[0] == "R":
|
|
direction = "E"
|
|
for _ in range(step):
|
|
we += 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif steps[0] == "L":
|
|
direction = "W"
|
|
for _ in range(step):
|
|
we -= 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif direction == "S":
|
|
if steps[0] == "R":
|
|
direction = "W"
|
|
for _ in range(step):
|
|
we -= 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif steps[0] == "L":
|
|
direction = "E"
|
|
for _ in range(step):
|
|
we += 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif direction == "W":
|
|
if steps[0] == "R":
|
|
direction = "N"
|
|
for _ in range(step):
|
|
ns += 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif steps[0] == "L":
|
|
direction = "S"
|
|
for _ in range(step):
|
|
ns -= 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif direction == "E":
|
|
if steps[0] == "R":
|
|
direction = "S"
|
|
for _ in range(step):
|
|
ns -= 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
elif steps[0] == "L":
|
|
direction = "N"
|
|
for _ in range(step):
|
|
ns += 1
|
|
if part2:
|
|
check_position((we,ns))
|
|
return we, ns, direction
|
|
|
|
if __name__ == "__main__":
|
|
position = (0,0,"N")
|
|
pos_list = [(0,0)]
|
|
part2 = True
|
|
input_list = read_file(file)
|
|
#input_list = ex1
|
|
#input_list = ex2
|
|
#input_list = ex3
|
|
# input_list = ex4
|
|
for elem in input_list:
|
|
position = go(position, elem)
|
|
|
|
solution = abs(position[0]) + abs(position[1])
|
|
|
|
# print(input_list)
|
|
print(f'Solution P1: {solution}')
|
|
print(f'Runtime: {time()-start_time:.2f} s') |