AoC/2023/days/03/part1.py

48 lines
1.7 KiB
Python
Executable File

with open("data/input.txt", "r") as f:
data = f.read()
table = [
[item for item in row]
for row in data.split("\n")
]
symbols = "&~\"#'{([-|`_\\^`])}@)]=+}$£%*!§/:;,?<>"
parts = []
positions = set()
for i in range(len(table)):
for j in range(len(table[i])):
letter = table[i][j]
if letter in symbols:
found = False
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
y = i + dx
x = j + dy
if x >= 0 and x < len(table[i]) and y >= 0 and y <= len(table):
number = ""
digit = table[y][x]
if digit != "." and digit.isdigit():
number = digit
found = True
# Extend right
shift = 1
idx = x + shift
while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit():
number = number + table[y][idx]
idx += shift
position = (y, idx)
# Extend left
shift = -1
idx = x + shift
while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit():
number = table[y][idx] + number
idx += shift
if position not in positions:
positions.add(position)
parts.append(int(number))
print(sum(parts))