From 51275dd539bdf6843fa11e4e48fd41feb57bb852 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Capelle?= Date: Sat, 14 Dec 2024 22:07:05 +0100 Subject: [PATCH] 2021 day 11. --- src/holt59/aoc/2021/day11.py | 61 ++++++++++++++++++++- src/holt59/aoc/inputs/holt59/2021/day11.txt | 10 ++++ src/holt59/aoc/inputs/tests/2021/day11.txt | 10 ++++ 3 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/holt59/aoc/2021/day11.py b/src/holt59/aoc/2021/day11.py index 07e201e..d987fd7 100644 --- a/src/holt59/aoc/2021/day11.py +++ b/src/holt59/aoc/2021/day11.py @@ -1,7 +1,66 @@ +import itertools as it from typing import Any, Iterator from ..base import BaseSolver +def do_step(values: list[list[int]]) -> tuple[list[list[int]], set[tuple[int, int]]]: + values = [[c + 1 for c in r] for r in values] + flashed: set[tuple[int, int]] = set() + + while True: + found = False + + for i_row, row in enumerate(values): + for i_col, col in enumerate(row): + if col <= 9 or (i_row, i_col) in flashed: + continue + + found = True + flashed.add((i_row, i_col)) + for dr, dc in it.product((-1, 0, 1), repeat=2): + if 0 <= i_row + dr < len(values) and 0 <= i_col + dc < len( + values[0] + ): + values[i_row + dr][i_col + dc] += 1 + + if not found: + break + + for i, j in flashed: + values[i][j] = 0 + + return values, flashed + + class Solver(BaseSolver): - def solve(self, input: str) -> Iterator[Any]: ... + def print_grid(self, values: list[list[int]], flashed: set[tuple[int, int]]): + for i_row, row in enumerate(values): + s_row = "" + for i_col, col in enumerate(row): + if (i_row, i_col) in flashed: + s_row += f"\033[0;31m{col}\033[0;00m" + else: + s_row += str(col) + self.logger.info(s_row) + self.logger.info("") + + def solve(self, input: str) -> Iterator[Any]: + values_0 = [[int(c) for c in r] for r in input.splitlines()] + + values = values_0 + total_flashed: int = 0 + for _ in range(100): + values, flashed = do_step(values) + total_flashed += len(flashed) + + yield total_flashed + + n_cells = len(values) * len(values[0]) + flashed: set[tuple[int, int]] = set() + values, step = values_0, 0 + while len(flashed) != n_cells: + values, flashed = do_step(values) + step += 1 + + yield step diff --git a/src/holt59/aoc/inputs/holt59/2021/day11.txt b/src/holt59/aoc/inputs/holt59/2021/day11.txt index e69de29..e462b30 100644 --- a/src/holt59/aoc/inputs/holt59/2021/day11.txt +++ b/src/holt59/aoc/inputs/holt59/2021/day11.txt @@ -0,0 +1,10 @@ +4738615556 +6744423741 +2812868827 +8844365624 +4546674266 +4518674278 +7457237431 +4524873247 +3153341314 +3721414667 diff --git a/src/holt59/aoc/inputs/tests/2021/day11.txt b/src/holt59/aoc/inputs/tests/2021/day11.txt index e69de29..03743f6 100644 --- a/src/holt59/aoc/inputs/tests/2021/day11.txt +++ b/src/holt59/aoc/inputs/tests/2021/day11.txt @@ -0,0 +1,10 @@ +5483143223 +2745854711 +5264556173 +6141336146 +6357385478 +4167524645 +2176841721 +6882881134 +4846848554 +5283751526