You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.6 KiB
Python
61 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Part 1
|
|
"""
|
|
|
|
import sys
|
|
import re
|
|
|
|
ENGINE_MAP = []
|
|
|
|
for line in sys.stdin.readlines():
|
|
line = line.strip()
|
|
ENGINE_MAP.append(line)
|
|
|
|
print()
|
|
|
|
|
|
def get_num(coordinates: tuple):
|
|
"""Get number from ENGINE_MAP"""
|
|
x, y = coordinates
|
|
line = ENGINE_MAP[x]
|
|
number = line[y]
|
|
while y < len(line) - 1 and re.match(r"[0-9]", line[y + 1]):
|
|
y += 1
|
|
number += line[y]
|
|
number = int(number)
|
|
return number
|
|
|
|
|
|
RESULT = 0
|
|
|
|
for x, line in enumerate(ENGINE_MAP):
|
|
for y, symbol in enumerate(line):
|
|
if symbol == "*":
|
|
symbol_numbers = set()
|
|
# print(f"{x},{y}: {symbol}")
|
|
for d_x in [-1, 0, 1]:
|
|
for d_y in [-1, 0, 1]:
|
|
coord_x = x + d_x
|
|
coord_y = y + d_y
|
|
if coord_x < 0 or coord_x > len(ENGINE_MAP) - 1:
|
|
continue
|
|
if coord_y < 0 or coord_y > len(ENGINE_MAP[coord_x]) - 1:
|
|
continue
|
|
if re.match(r"[0-9]", ENGINE_MAP[coord_x][coord_y]):
|
|
while coord_y > 0 and re.match(
|
|
r"[0-9]", ENGINE_MAP[coord_x][coord_y - 1]
|
|
):
|
|
coord_y -= 1
|
|
symbol_numbers.add((coord_x, coord_y))
|
|
if len(symbol_numbers) == 2:
|
|
num_1 = get_num(list(symbol_numbers)[0])
|
|
num_2 = get_num(list(symbol_numbers)[1])
|
|
gear_ratio = num_1 * num_2
|
|
print(f"Gear found at {x},{y}. {gear_ratio=}")
|
|
RESULT += gear_ratio
|
|
|
|
|
|
print()
|
|
print(RESULT)
|