From d19fbb93613785e94992c174d8e9868b6e0b936a Mon Sep 17 00:00:00 2001 From: setop Date: Sun, 3 Dec 2023 10:47:21 +0100 Subject: [PATCH] day 3, parcours de grille --- d03/part1.py | 32 ++++++++++++++++++++++++++++++++ d03/part2.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 d03/part1.py create mode 100644 d03/part2.py diff --git a/d03/part1.py b/d03/part1.py new file mode 100644 index 0000000..1c6bdd4 --- /dev/null +++ b/d03/part1.py @@ -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)) diff --git a/d03/part2.py b/d03/part2.py new file mode 100644 index 0000000..c5ce513 --- /dev/null +++ b/d03/part2.py @@ -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)