from lib import * EXAMPLE = "R5, L5, R5, R3" EXAMPLE = "R2, R2, R2" EXAMPLE = "R8, R4, R4, R8" DIRS = "NESW" MOVES = { "N": (-1, 0), "E": (0, 1), "S": (1, 0), "W": (0, -1), } def solve(input: Input, second=False): steps = input.text.split(", ") coord, dir = (0, 0), "N" allcoords = set([coord]) for step in steps: turn, nsteps = step[0], int(step[1:]) os = -1 if turn == "L" else 1 dir = DIRS[(DIRS.index(dir) + os) % len(DIRS)] rowo, colo = MOVES[dir] if second: for n in range(1, nsteps): tcoord = (coord[0] + rowo * n, coord[1] + colo * n) if tcoord in allcoords: return abs(tcoord[0]) + abs(tcoord[1]) allcoords.add(tcoord) coord = (coord[0] + rowo * nsteps, coord[1] + colo * nsteps) return abs(coord[0]) + abs(coord[1]) def main(): DAY_INPUT = "i1.txt" print("Solution 1:", solve(Input(DAY_INPUT))) print("Solution 2:", solve(Input(DAY_INPUT), True)) if __name__ == "__main__": main()