Advent_of_Code/2023/03/main.py

79 lines
1.5 KiB
Python
Raw Permalink Normal View History

2023-12-03 16:58:11 +00:00
def is_symbol(c):
symbols = list("+-*/=#%&$@")
res = c in symbols
return res
def get_num(row, col):
cursor = col
num = 0
num_left = -1
num_right = -1
if file[row][col].isdigit():
num_left = cursor
while file[row][cursor].isdigit() and cursor >= 0:
num_left = cursor
cursor -= 1
cursor = col
while file[row][cursor].isdigit() and cursor <= len(file[row]):
num_right = cursor
cursor += 1
num = int(file[row][num_left:num_right+1])
s = list(file[row])
for i in range(num_left, num_right+1):
s[i] = "."
file[row] = "".join(s)
return num
def get_adj_numbers_sum(row, col):
partial_sum = 0
gear_product = 0
gear_product_parts = []
tl = get_num(row-1, col-1)
t = get_num(row+1, col)
tr = get_num(row-1, col+1)
l = get_num(row, col-1)
r = get_num(row, col+1)
bl = get_num(row+1, col-1)
b = get_num(row-1, col)
br = get_num(row+1, col+1)
adj = [tl,t,tr,l,r,bl,b,br]
if file[row][col] == "*":
for i in range(len(adj)):
if adj[i] >= 1:
gear_product_parts.append(adj[i])
if len(gear_product_parts) == 2:
gear_product = gear_product_parts[0] * gear_product_parts[1]
partial_sum = tl+t+tr+l+r+bl+b+br
return partial_sum, gear_product
def solve(file):
part_1 = 0
part_2 = 0
for i in range(1, len(file)-1):
for j in range(len(file[i])):
if is_symbol(file[i][j]):
res = get_adj_numbers_sum(i, j)
part_1, part_2 = part_1 + res[0], part_2 + res[1]
return part_1, part_2
file = open("input.txt", "r").readlines()
ans1, ans2 = solve(file)
print(f"Part 1: {ans1}\nPart 2: {ans2}")