aoc/2023/day3/main.py
2023-12-04 10:24:41 +01:00

79 lines
2.1 KiB
Python

matrix = []
with open("input.txt", "r") as f:
for line in f:
matrix.append(line.strip())
number_extends = []
for rowi, row in enumerate(matrix):
number_extends.append([])
last_chari = -1
for chari, char in enumerate(row):
if chari <= last_chari:
continue
if char.isnumeric():
first_chari = chari
last_chari = chari
charit = chari + 1
while charit < len(row):
if row[charit].isnumeric():
last_chari = charit
charit += 1
else:
break
number_extends[rowi].append((first_chari, last_chari))
numbers = []
gears = {}
for rowi, number_extend_row in enumerate(number_extends):
for start, end in number_extend_row:
number = int(matrix[rowi][start : (end + 1)])
def symbol_in_range(rowii, s, e):
if rowii < 0 or rowii >= len(matrix):
return False
e += 1
if s < 0:
s = 0
if e >= len(matrix[rowii]):
e = len(matrix[rowii]) - 1
for i in range(s, e):
char = matrix[rowii][i]
if char == "*":
# Found a gear
if (rowii, i) in gears:
gears[(rowii, i)].append(number)
else:
gears[(rowii, i)] = [number]
if (not char.isnumeric()) and (char != "."):
return True
return False
if (
symbol_in_range(rowi - 1, start - 1, end + 1)
or symbol_in_range(rowi, start - 1, end + 1)
or symbol_in_range(rowi + 1, start - 1, end + 1)
):
numbers.append(number)
part1 = 0
for n in numbers:
part1 += n
print("part1", part1)
gear_ratios = []
for (row, col), gear_numbers in gears.items():
if len(gear_numbers) == 2:
gear_ratios.append(gear_numbers[0] * gear_numbers[1])
part2 = 0
for n in gear_ratios:
part2 += n
print("part2", part2)