Optimized solution

This commit is contained in:
2026-06-21 19:46:20 +02:00
parent f4aa799bac
commit d78e9d6c63

View File

@@ -21,41 +21,29 @@
# ^v^v^v^v^v delivers a bunch of presents to some very lucky children at # ^v^v^v^v^v delivers a bunch of presents to some very lucky children at
# only 2 houses. # only 2 houses.
from typing import Tuple
with open("files/P3.txt") as f: with open("files/P3.txt") as f:
moves = [line for line in f.read().strip().split()][0] moves = [line for line in f.read().strip()]
def move_up(pos: Tuple[int, int]) -> Tuple[int, int]: Position = tuple[int, int]
return pos[0], pos[1] + 1 DIRECTIONS: dict[str, Position] = {
"^": (0, 1),
"v": (0, -1),
def move_down(pos: Tuple[int, int]) -> Tuple[int, int]: "<": (-1, 0),
return pos[0], pos[1] - 1 ">": (1, 0),
}
def move_left(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0] - 1, pos[1]
def move_right(pos: Tuple[int, int]) -> Tuple[int, int]:
return pos[0] + 1, pos[1]
def part_1() -> None: def part_1() -> None:
pos = [(0, 0)] x, y = 0, 0
visited: set[Position] = {(x, y)}
for move in moves: for move in moves:
if move == "^": delta_x, delta_y = DIRECTIONS[move]
pos.append(move_up(pos[-1])) x += delta_x
elif move == "v": y += delta_y
pos.append(move_down(pos[-1])) visited.add((x, y))
elif move == "<":
pos.append(move_left(pos[-1]))
elif move == ">":
pos.append(move_right(pos[-1]))
print(f"{len(set(pos))} houses receive at least one present") print(f"{len(visited)} houses receive at least one present")
# --- Part Two --- # --- Part Two ---
@@ -81,33 +69,23 @@ def part_1() -> None:
def part_2(): def part_2():
santa = [(0, 0)] x_santa, y_santa = 0, 0
robo_santa = [(0, 0)] x_robo, y_robo = 0, 0
for idx, move in enumerate(moves): visited: set[Position] = {(0, 0)}
if move == "^":
if idx % 2 == 0:
santa.append(move_up(santa[-1]))
else:
robo_santa.append(move_up(robo_santa[-1]))
elif move == "v":
if idx % 2 == 0:
santa.append(move_down(santa[-1]))
else:
robo_santa.append(move_down(robo_santa[-1]))
elif move == "<":
if idx % 2 == 0:
santa.append(move_left(santa[-1]))
else:
robo_santa.append(move_left(robo_santa[-1]))
elif move == ">":
if idx % 2 == 0:
santa.append(move_right(santa[-1]))
else:
robo_santa.append(move_right(robo_santa[-1]))
print( for idx, move in enumerate(moves):
f"{len(set(santa + robo_santa))} houses receive at least one present" delta_x, delta_y = DIRECTIONS[move]
) # santa's turn
if idx % 2:
x_santa += delta_x
y_santa += delta_y
visited.add((x_santa, y_santa))
else:
x_robo += delta_x
y_robo += delta_y
visited.add((x_robo, y_robo))
print(f"{len(visited)} houses receive at least one present")
if __name__ == "__main__": if __name__ == "__main__":