52 lines
1.8 KiB
Python
Executable File
52 lines
1.8 KiB
Python
Executable File
import numpy as np
|
|
|
|
with open("data/input.txt", "r") as f:
|
|
data = f.read()
|
|
|
|
table = [
|
|
[item for item in row]
|
|
for row in data.split("\n")
|
|
]
|
|
|
|
symbols = "&~\"#'{([-|`_\\^`])}@)]=+}$£%*!§/:;,?<>"
|
|
|
|
|
|
gears = []
|
|
|
|
|
|
for i in range(len(table)):
|
|
for j in range(len(table[i])):
|
|
letter = table[i][j]
|
|
if letter == "*":
|
|
gear_numbers = []
|
|
positions = set()
|
|
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)
|
|
gear_numbers.append(int(number))
|
|
if len(gear_numbers) == 2:
|
|
gears.append(np.prod(gear_numbers))
|
|
print(sum(gears))
|