From 2c5c51e05f888bd4fff2ab47b96566cfa0af4769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Capelle?= Date: Sat, 14 Dec 2024 22:29:20 +0100 Subject: [PATCH] 2021 day 12. --- src/holt59/aoc/2021/day12.py | 47 ++++++++++++++++++++- src/holt59/aoc/inputs/holt59/2021/day12.txt | 26 ++++++++++++ src/holt59/aoc/inputs/tests/2021/day12.txt | 18 ++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/holt59/aoc/2021/day12.py b/src/holt59/aoc/2021/day12.py index 07e201e..2bdf8ba 100644 --- a/src/holt59/aoc/2021/day12.py +++ b/src/holt59/aoc/2021/day12.py @@ -1,7 +1,50 @@ -from typing import Any, Iterator +import string +from collections import defaultdict +from functools import cache +from typing import Any, Iterator, Mapping, Sequence from ..base import BaseSolver +@cache +def is_small(node: str): + return all(c in string.ascii_lowercase for c in node) + + +def enumerate_paths( + neighbors: Mapping[str, Sequence[str]], + duplicate_smalls: int = 0, + start: str = "start", + current: tuple[str, ...] = ("start",), +) -> Iterator[tuple[str, ...]]: + if start == "end": + yield current + + for neighbor in neighbors[start]: + if not is_small(neighbor): + yield from enumerate_paths( + neighbors, duplicate_smalls, neighbor, current + (neighbor,) + ) + elif neighbor not in current: + yield from enumerate_paths( + neighbors, duplicate_smalls, neighbor, current + (neighbor,) + ) + elif duplicate_smalls > 0: + yield from enumerate_paths( + neighbors, duplicate_smalls - 1, neighbor, current + (neighbor,) + ) + + class Solver(BaseSolver): - def solve(self, input: str) -> Iterator[Any]: ... + def solve(self, input: str) -> Iterator[Any]: + neighbors: dict[str, list[str]] = defaultdict(list) + + for row in input.splitlines(): + a, b = row.split("-") + if a != "end" and b != "start": + neighbors[a].append(b) + if b != "end" and a != "start": + neighbors[b].append(a) + + yield len(list(enumerate_paths(neighbors))) + yield len(list(enumerate_paths(neighbors, 1))) diff --git a/src/holt59/aoc/inputs/holt59/2021/day12.txt b/src/holt59/aoc/inputs/holt59/2021/day12.txt index e69de29..4d27f29 100644 --- a/src/holt59/aoc/inputs/holt59/2021/day12.txt +++ b/src/holt59/aoc/inputs/holt59/2021/day12.txt @@ -0,0 +1,26 @@ +xq-XZ +zo-yr +CT-zo +yr-xq +yr-LD +xq-ra +np-zo +end-LD +np-LD +xq-kq +start-ra +np-kq +LO-end +start-xq +zo-ra +LO-np +XZ-start +zo-kq +LO-yr +kq-XZ +zo-LD +kq-ra +XZ-yr +LD-ws +np-end +kq-yr diff --git a/src/holt59/aoc/inputs/tests/2021/day12.txt b/src/holt59/aoc/inputs/tests/2021/day12.txt index e69de29..65f3833 100644 --- a/src/holt59/aoc/inputs/tests/2021/day12.txt +++ b/src/holt59/aoc/inputs/tests/2021/day12.txt @@ -0,0 +1,18 @@ +fs-end +he-DX +fs-he +start-DX +pj-DX +end-zg +zg-sl +zg-pj +pj-he +RW-he +fs-DX +pj-RW +zg-RW +start-pj +he-WI +zg-he +pj-fs +start-RW