From 4fce053060006a9d38d695033b2ea76ab87064ac Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 3 Dec 2023 12:46:22 +0000 Subject: day 3 --- 3.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 3.py diff --git a/3.py b/3.py new file mode 100644 index 0000000..990c9ef --- /dev/null +++ b/3.py @@ -0,0 +1,39 @@ +import re +from collections import defaultdict +from collections.abc import Iterator +from functools import reduce +from operator import mul +from sys import stdin + +num_re = re.compile("[0-9]+") + +inp = [line.rstrip() for line in stdin] + + +def find_adjacent_symbols( + inp: list[str], ly: int, sx: int, ex: int +) -> Iterator[tuple[int, int]]: + for x in range(max(0, sx - 1), min(ex + 1, len(l))): + for y in range(max(0, ly - 1), min(ly + 2, len(inp))): + if y == ly and sx <= x < ex: + continue + if inp[y][x] != "." and not inp[y][x].isdigit(): + yield x, y + + +p1 = 0 +p2_gears: defaultdict[tuple[int, int], list[int]] = defaultdict(list) +for ly, l in enumerate(inp): + for match in num_re.finditer(l): + value = int(match.group()) + sx, ex = match.span() + is_part_no = False + for x, y in find_adjacent_symbols(inp, ly, sx, ex): + if inp[y][x] == "*": + p2_gears[x, y].append(value) + is_part_no = True + if is_part_no: + p1 += value + +print(p1) +print(sum(reduce(mul, nums) for nums in p2_gears.values() if len(nums) > 1)) -- cgit v1.2.3-54-g00ecf