From f41c4cd0980b6ce21ac7cb12feba6d6ffd9d8358 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Mon, 6 Dec 2021 13:57:04 +0100 Subject: [PATCH] Solve day 6 --- 2021/day06_lanternfish.py | 56 +++++++++++++++++++++++++++++++++++++++ 2021/inputs/day06 | 1 + 2021/inputs/day06-test1 | 1 + 3 files changed, 58 insertions(+) create mode 100644 2021/day06_lanternfish.py create mode 100644 2021/inputs/day06 create mode 100644 2021/inputs/day06-test1 diff --git a/2021/day06_lanternfish.py b/2021/day06_lanternfish.py new file mode 100644 index 0000000..8022efe --- /dev/null +++ b/2021/day06_lanternfish.py @@ -0,0 +1,56 @@ +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Dict, Iterator, List + + +def main(filename: str, expected_part_1: int = None, expected_part_2: int = None): + print(f"\n+ Running on {filename}") + with open(filename) as f: + data = f.read().strip().split("\n") + + data = parse_data(data) + solution_part_1 = solve_part_1(data) + + print(f"1. Found {solution_part_1}") + if expected_part_1: + assert expected_part_1 == solution_part_1 + + solution_part_2 = solve_part_2(data) + print(f"2. Found {solution_part_2}") + if expected_part_2: + assert expected_part_2 == solution_part_2 + + +def parse_data(data: List[str]) -> Dict[int, int]: + dct = defaultdict(int) + for x in map(int, data[0].split(",")): + dct[x] += 1 + return dct + + +def solve_part_1(data) -> int: + for _ in range(80): + data = _run_day(data) + return sum(data.values()) + + +def _run_day(data: Dict[int, int]) -> Dict[int, int]: + new_data = defaultdict(int) + for k, v in data.items(): + if k == 0: + new_data[6] += v + new_data[8] += v + else: + new_data[k - 1] += v + return new_data + + +def solve_part_2(data) -> int: + for _ in range(256): + data = _run_day(data) + return sum(data.values()) + + +if __name__ == "__main__": + main("inputs/day06-test1", expected_part_1=5934, expected_part_2=26984457539) + main("inputs/day06", expected_part_1=345793) diff --git a/2021/inputs/day06 b/2021/inputs/day06 new file mode 100644 index 0000000..3d35529 --- /dev/null +++ b/2021/inputs/day06 @@ -0,0 +1 @@ +3,1,5,4,4,4,5,3,4,4,1,4,2,3,1,3,3,2,3,2,5,1,1,4,4,3,2,4,2,4,1,5,3,3,2,2,2,5,5,1,3,4,5,1,5,5,1,1,1,4,3,2,3,3,3,4,4,4,5,5,1,3,3,5,4,5,5,5,1,1,2,4,3,4,5,4,5,2,2,3,5,2,1,2,4,3,5,1,3,1,4,4,1,3,2,3,2,4,5,2,4,1,4,3,1,3,1,5,1,3,5,4,3,1,5,3,3,5,4,2,3,4,1,2,1,1,4,4,4,3,1,1,1,1,1,4,2,5,1,1,2,1,5,3,4,1,5,4,1,3,3,1,4,4,5,3,1,1,3,3,3,1,1,5,4,2,5,1,1,5,5,1,4,2,2,5,3,1,1,3,3,5,3,3,2,4,3,2,5,2,5,4,5,4,3,2,4,3,5,1,2,2,4,3,1,5,5,1,3,1,3,2,2,4,5,4,2,3,2,3,4,1,3,4,2,5,4,4,2,2,1,4,1,5,1,5,4,3,3,3,3,3,5,2,1,5,5,3,5,2,1,1,4,2,2,5,1,4,3,3,4,4,2,3,2,1,3,1,5,2,1,5,1,3,1,4,2,4,5,1,4,5,5,3,5,1,5,4,1,3,4,1,1,4,5,5,2,1,3,3 diff --git a/2021/inputs/day06-test1 b/2021/inputs/day06-test1 new file mode 100644 index 0000000..a7af2b1 --- /dev/null +++ b/2021/inputs/day06-test1 @@ -0,0 +1 @@ +3,4,3,1,2 \ No newline at end of file