My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add solution for 2023/03

+41
+41
2023/day03.py
··· 1 + import fileinput 2 + 3 + SYMBOLS = {} 4 + PARTS = [] 5 + 6 + # Parse input. 7 + for y, line in enumerate(fileinput.input()): 8 + num = '' 9 + start = None 10 + for x, c in enumerate(line.strip()): 11 + if not c.isdigit() and c != '.': 12 + SYMBOLS[x, y] = c 13 + 14 + if c.isdigit(): 15 + if not num: 16 + start = x 17 + num += c 18 + elif num: 19 + PARTS.append((int(num), y, start, x - 1)) 20 + num = '' 21 + 22 + if num: 23 + PARTS.append((int(num), y, start, x - 1)) 24 + 25 + # Solve problem. 26 + part_1_seen = set() 27 + part_2 = 0 28 + 29 + for x, y in SYMBOLS: 30 + adj = [] 31 + for i, (n, yy, start, end) in enumerate(PARTS): 32 + if yy - 1 <= y <= yy + 1 and start - 1 <= x <= end + 1: 33 + part_1_seen.add(i) 34 + adj.append(n) 35 + 36 + if len(adj) == 2 and SYMBOLS[x, y] == '*': 37 + part_2 += adj[0] * adj[1] 38 + 39 + 40 + print("Part 1:", sum(PARTS[i][0] for i in part_1_seen)) 41 + print("Part 2:", part_2)