summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTomasz Kramkowski <tomasz@kramkow.ski>2023-12-03 12:46:22 +0000
committerTomasz Kramkowski <tomasz@kramkow.ski>2023-12-03 12:46:22 +0000
commit4fce053060006a9d38d695033b2ea76ab87064ac (patch)
tree990dbf9df738eae06da0c6a1f8740451da3943ac
parent3bc9b83494916ed3928556dae7773664e70c6f21 (diff)
downloadaoc2023-4fce053060006a9d38d695033b2ea76ab87064ac.tar.gz
aoc2023-4fce053060006a9d38d695033b2ea76ab87064ac.tar.xz
aoc2023-4fce053060006a9d38d695033b2ea76ab87064ac.zip
day 3
-rw-r--r--3.py39
1 files changed, 39 insertions, 0 deletions
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))