Skip to content

Commit 99c93b2

Browse files
committed
Solve 2023 day 3 part 1
1 parent 9179a8b commit 99c93b2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

2023/Day3/python/solve.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from pathlib import Path
2+
import re
3+
4+
def has_adjacent_symbol(matrix, i, start, end):
5+
pattern = re.compile("[0-9\.]")
6+
# Left
7+
if start > 0 and matrix[i][start - 1] != "." and not bool(pattern.match(matrix[i][start - 1])):
8+
return True
9+
# Right
10+
if end < len(matrix[i]) and matrix[i][end] != "." and not bool(pattern.match(matrix[i][end])):
11+
return True
12+
13+
# Above
14+
if i > 0:
15+
above = matrix[i - 1][max(0, start - 1):min(len(matrix[i]), end + 1)]
16+
for sym in above:
17+
if not bool(pattern.match(sym)) and sym != ".":
18+
return True
19+
20+
# Below
21+
if i < len(matrix) - 1:
22+
below = matrix[i + 1][max(0, start - 1):min(len(matrix[i]), end + 1)]
23+
for sym in below:
24+
if not bool(pattern.match(sym)) and sym != ".":
25+
return True
26+
27+
return False
28+
29+
30+
def part1(lines):
31+
matrix = [list(line) for line in lines]
32+
engine_parts = []
33+
34+
for i, line in enumerate(matrix):
35+
j = 0
36+
while j < len(line):
37+
if line[j].isdigit():
38+
start = j
39+
while j < len(line) and line[j].isdigit():
40+
j += 1
41+
end = j
42+
43+
if has_adjacent_symbol(matrix, i, start, end):
44+
number = int("".join(line[start:end]))
45+
engine_parts.append(number)
46+
else:
47+
j += 1
48+
49+
return sum(engine_parts)
50+
51+
52+
with (Path(__file__).parent / "../input.txt").open() as f:
53+
lines = list(map(lambda l: l.strip(), f.readlines()))
54+
print(part1(lines))

0 commit comments

Comments
 (0)