aoc2023/d03/part2.py

34 lines
770 B
Python
Raw Permalink Normal View History

2023-12-03 09:47:21 +00:00
import sys
from collections import defaultdict as dd
G = [ list(l[:-1]) for l in sys.stdin.readlines()]
W = len(G[0])
H = len(G)
def get_G(x,y):
return '.' if x<0 or y<0 or x>W-1 or y>H-1 else G[y][x]
c = 0 # current star
valid = None
Rs = dd(list)
for y in range(H):
for x in range(W):
i = get_G(x,y)
if not i.isdigit():
# appent current if valid and reset
if valid:
Rs[valid].append(c)
valid = None
c = 0
else:
c = c*10+int(i)
for dx in [-1,0,1]:
for dy in [-1,0,1]:
if '*' == get_G(x+dx,y+dy):
valid = (x+dx,y+dy)
2023-12-06 22:41:41 +00:00
print(
sum( v[0] * v[1] for _,v in Rs.items() if len(v)==2)
)