File handling for API.

This commit is contained in:
Mikael CAPELLE
2024-12-10 15:38:00 +01:00
parent 3c544c559b
commit 46558672e8
18 changed files with 288 additions and 160 deletions

View File

@@ -33,10 +33,14 @@ MAPPINGS: dict[Direction, tuple[int, int, Direction]] = {
class Solver(BaseSolver):
def print_shortest_path(
self,
name: str,
grid: list[list[int]],
target: tuple[int, int],
per_cell: dict[tuple[int, int], list[tuple[Label, int]]],
):
if not self.files:
return
assert len(per_cell[target]) == 1
label = per_cell[target][0][0]
@@ -74,8 +78,9 @@ class Solver(BaseSolver):
p_grid[0][0] = f"\033[92m{grid[0][0]}\033[0m"
for row in p_grid:
self.logger.info("".join(row))
self.files.create(
name, "\n".join("".join(row) for row in p_grid).encode(), True
)
def shortest_many_paths(self, grid: list[list[int]]) -> dict[tuple[int, int], int]:
n_rows, n_cols = len(grid), len(grid[0])
@@ -129,6 +134,7 @@ class Solver(BaseSolver):
def shortest_path(
self,
name: str,
grid: list[list[int]],
min_straight: int,
max_straight: int,
@@ -217,8 +223,7 @@ class Solver(BaseSolver):
),
)
if self.verbose:
self.print_shortest_path(grid, target, per_cell)
self.print_shortest_path(f"shortest-path_{name}.txt", grid, target, per_cell)
return per_cell[target][0][1]
@@ -227,7 +232,7 @@ class Solver(BaseSolver):
estimates = self.shortest_many_paths(data)
# part 1
yield self.shortest_path(data, 1, 3, lower_bounds=estimates)
yield self.shortest_path("answer_1", data, 1, 3, lower_bounds=estimates)
# part 2
yield self.shortest_path(data, 4, 10, lower_bounds=estimates)
yield self.shortest_path("answer_2", data, 4, 10, lower_bounds=estimates)