2024 day 6, brute force.

This commit is contained in:
Mikaël Capelle
2024-12-06 06:50:35 +01:00
parent cd6f97cd7e
commit 2c1a0b919b
3 changed files with 238 additions and 2 deletions

View File

@@ -1,10 +1,106 @@
import sys
from typing import TypeAlias
def move(
lines: list[str], pos: tuple[int, int], dir: tuple[int, int]
) -> tuple[tuple[int, int] | None, list[tuple[int, int]]]:
n_rows, n_cols = len(lines), len(lines[0])
row, col = pos
marked: list[tuple[int, int]] = []
while True:
marked.append((row, col))
if not (0 <= row + dir[0] < n_rows and 0 <= col + dir[1] < n_cols):
pos = None
break
if lines[row + dir[0]][col + dir[1]] != ".":
pos = (row, col)
break
row += dir[0]
col += dir[1]
return pos, marked
def print_grid(
lines: list[str], marked: set[tuple[int, int]], current_pos: tuple[int, int] | None
):
chars = list(map(list, lines))
for i, j in marked:
chars[i][j] = "X"
if current_pos:
chars[current_pos[0]][current_pos[1]] = "T"
for line in chars:
print("".join(line))
print()
ROTATE = {(-1, 0): (0, 1), (0, 1): (1, 0), (1, 0): (0, -1), (0, -1): (-1, 0)}
lines = sys.stdin.read().splitlines()
n_rows, n_cols = len(lines), len(lines[0])
start_pos = next(
(i, j) for i in range(n_rows) for j in range(n_cols) if lines[i][j] == "^"
)
lines[start_pos[0]] = lines[start_pos[0]].replace("^", ".")
answer_1 = ...
# part 1
marked: set[tuple[int, int]] = set()
answer_2 = ...
current_pos: tuple[int, int] | None = start_pos
current_dir = (-1, 0)
while current_pos is not None:
# print_grid(lines, marked, current_pos)
new_pos, new_marked = move(lines, current_pos, current_dir)
marked = marked.union(new_marked)
current_pos = new_pos
current_dir = ROTATE[current_dir]
# print_grid(lines, marked, current_pos)
answer_1 = len(marked)
answer_2 = 0
for row in range(n_rows):
for col in range(n_cols):
if (row, col) == start_pos or lines[row][col] != ".":
continue
chars = list(map(list, lines))
chars[row][col] = "#"
current_pos = start_pos
current_dir = (-1, 0)
found: set[tuple[tuple[int, int], tuple[int, int]]] = set()
while current_pos is not None:
if current_pos != start_pos:
found.add((current_pos, current_dir))
new_pos, new_marked = move(
["".join(line) for line in chars], current_pos, current_dir
)
current_pos = new_pos
current_dir = ROTATE[current_dir]
if (current_pos, current_dir) in found:
print(row, col)
answer_2 += 1
break
print(f"answer 1 is {answer_1}")
print(f"answer 2 is {answer_2}")