day 3, parcours de grille

This commit is contained in:
setop 2023-12-03 10:47:21 +01:00
parent e59e7fab23
commit d19fbb9361
2 changed files with 67 additions and 0 deletions

32
d03/part1.py Normal file
View File

@ -0,0 +1,32 @@
import sys
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]
def is_sym(a:str) -> bool:
return a != '.' and not a.isdigit()
c = 0 # current
valid = False
Ns = [] # all part numbers
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:
Ns.append(c)
valid = False
c = 0
else:
c = c*10+int(i)
for dx in [-1,0,1]:
for dy in [-1,0,1]:
valid |= is_sym(get_G(x+dx,y+dy))
print(sum(Ns))

35
d03/part2.py Normal file
View File

@ -0,0 +1,35 @@
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)
S = 0
for _,v in Rs.items():
if len(v)==2:
S += v[0] * v[1]
print(S)