-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-3a.py
60 lines (51 loc) · 1.24 KB
/
day-3a.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File: day-3a.py
# Purpose: Solve problem 1 on day 3 of advent of ocde
# https://adventofcode.com/2023/day/3
# Author: Robert Lowe
# Date: December 3, 2023
import sys
# read the grid and get its stats
grid=sys.stdin.readlines()
w = len(grid[0])
h = len(grid)
def neighborhood(x,y):
"""
Get all of the grid neighbors
"""
result = []
for nx in range(max(0, x-1), min(w, x+2)):
for ny in range(max(0, y-1), min(h, y+2)):
if x == nx and y == ny:
continue
result.append(grid[ny][nx])
return result
def is_part(x,y):
"""
Check to see if a number is a part.
"""
for c in neighborhood(x,y):
if not c.isdigit() and c != '.' and c != "\n":
return True
return False
#initial state
total=0
num=0
count=False
# go through the grid, parsing as we go
for y in range(0, h):
for x in range(0, w):
c = grid[y][x]
# handle non-number
if not c.isdigit():
if count:
total += num
num = 0
count = False
continue
num = num * 10 + int(c)
if is_part(x,y):
count = True
# add the last potential part
if count:
total += num
print(total)