Fix 2022 day 16 for progress API.

This commit is contained in:
Mikaël Capelle 2024-12-08 19:25:21 +01:00
parent 9d7ef94fa6
commit dd3f332870

View File

@ -6,8 +6,6 @@ import re
from collections import defaultdict from collections import defaultdict
from typing import Any, FrozenSet, Iterator, NamedTuple from typing import Any, FrozenSet, Iterator, NamedTuple
from tqdm import tqdm
from ..base import BaseSolver from ..base import BaseSolver
@ -62,12 +60,17 @@ def update_with_better(
node_at_times[flowing] = max(node_at_times[flowing], flow) node_at_times[flowing] = max(node_at_times[flowing], flow)
def part_1( # === MAIN ===
class Solver(BaseSolver):
def part_1(
self,
start_pipe: Pipe, start_pipe: Pipe,
max_time: int, max_time: int,
distances: dict[tuple[Pipe, Pipe], int], distances: dict[tuple[Pipe, Pipe], int],
relevant_pipes: FrozenSet[Pipe], relevant_pipes: FrozenSet[Pipe],
): ):
node_at_times: dict[int, dict[Pipe, dict[FrozenSet[Pipe], int]]] = defaultdict( node_at_times: dict[int, dict[Pipe, dict[FrozenSet[Pipe], int]]] = defaultdict(
lambda: defaultdict(lambda: defaultdict(lambda: 0)) lambda: defaultdict(lambda: defaultdict(lambda: 0))
) )
@ -99,15 +102,17 @@ def part_1(
for flow in nodes_of_pipe.values() for flow in nodes_of_pipe.values()
) )
def part_2(
def part_2( self,
start_pipe: Pipe, start_pipe: Pipe,
max_time: int, max_time: int,
distances: dict[tuple[Pipe, Pipe], int], distances: dict[tuple[Pipe, Pipe], int],
relevant_pipes: FrozenSet[Pipe], relevant_pipes: FrozenSet[Pipe],
): ):
def compute(pipes_for_me: FrozenSet[Pipe]) -> int: def compute(pipes_for_me: FrozenSet[Pipe]) -> int:
return part_1(start_pipe, max_time, distances, pipes_for_me) + part_1( return self.part_1(
start_pipe, max_time, distances, pipes_for_me
) + self.part_1(
start_pipe, max_time, distances, relevant_pipes - pipes_for_me start_pipe, max_time, distances, relevant_pipes - pipes_for_me
) )
@ -117,13 +122,8 @@ def part_2(
for relevant_pipes_1 in itertools.combinations(relevant_pipes, r) for relevant_pipes_1 in itertools.combinations(relevant_pipes, r)
] ]
return max(compute(comb) for comb in tqdm(combs)) return max(compute(comb) for comb in self.progress.wrap(combs))
# === MAIN ===
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]: def solve(self, input: str) -> Iterator[Any]:
lines = [line.strip() for line in input.splitlines()] lines = [line.strip() for line in input.splitlines()]
@ -153,7 +153,7 @@ class Solver(BaseSolver):
relevant_pipes = frozenset(pipe for pipe in pipes.values() if pipe.flow > 0) relevant_pipes = frozenset(pipe for pipe in pipes.values() if pipe.flow > 0)
# 1651, 1653 # 1651, 1653
yield part_1(pipes["AA"], 30, distances, relevant_pipes) yield self.part_1(pipes["AA"], 30, distances, relevant_pipes)
# 1707, 2223 # 1707, 2223
yield part_2(pipes["AA"], 26, distances, relevant_pipes) yield self.part_2(pipes["AA"], 26, distances, relevant_pipes)