AdventOfCode2023/day3-1.py
2023-12-03 03:57:45 -06:00

120 lines
3.6 KiB
Python

import time
valid_symbols = "#$%&*+-/=@"#"/,!@#$%^&*()_-+={}[]"
w,h = (140,140)
with open("input_day3.txt") as file:
lines = [line.rstrip() for line in file]
matrix = [[0 for x in range(w)] for y in range(h)]
for y in range(h):
for x in range(w):
matrix[y][x] = lines[y][x]
class number:
def __init__(self,x,y,length=1,num=0):
self.x = x
self.y = y
self.length = length
self.number = num
def append(self,num=0):
self.length+=1
self.number = int( f"{self.number}{num}" )
def is_valid(num:number) -> bool:
#but first check if number is valid
result = False
for offset in range(num.length):
x = num.x+offset
y = num.y
check_upperleft = True
check_upper = True
check_upperright = True
check_midleft = True
check_midright = True
check_lowerleft = True
check_lower = True
check_lowerright = True
#if on first y dont check above
if num.y == 0:
check_upperleft,check_upper,check_upperright = (False,False,False)
#if on last y dont check below
if num.y == h-1:
check_lowerleft,check_lower,check_lowerright = (False,False,False)
# if on left or right horizontal edge
if x == 0:
check_midleft = False
if x >= w-1:
check_midright = False
check_upperright = False
check_lowerright = False
#now do comparison
if check_upperleft:
if is_symbol(str(matrix[y-1][x-1])):
return True
if check_upper:
if is_symbol(str(matrix[y-1][x])):
return True
if check_upperright:
if is_symbol(str(matrix[y-1][x+1])):
return True
if check_midleft:
if is_symbol(str(matrix[y][x-1])):
return True
if check_midright:
if is_symbol(str(matrix[y][x+1])):
return True
if check_lowerleft:
if is_symbol(str(matrix[y+1][x-1])):
return True
if check_lower:
if is_symbol(str(matrix[y+1][x])):
return True
if check_lowerright:
if is_symbol(str(matrix[y+1][x+1])):
return True
return False
def is_symbol(c):
if c in valid_symbols:
return True
return False
numbers = []
#140x140 matrix
y=-1
#look at every element in matrix for a number
for line in lines:
#start new line
y+=1
is_on_number = False
for x in range(w):
c = line[x]
if c.isnumeric():
if not is_on_number:
#start a new number record
is_on_number = True
new_num = number(x,y,num=int(c))
elif x == w-1:
new_num.append(c)
if is_valid(new_num):
numbers.append(new_num)
print(new_num.number)
is_on_number = False
else:
#append to existing number
new_num.append(c)
else:
#not a number anymore so finish the number and add to num list if number is valid
if is_on_number:
if is_valid(new_num):
numbers.append(new_num)
#print(new_num.number)
#time.sleep(0.1)
is_on_number = False
sum = 0
for num in numbers:
sum+=int(num.number)
print(sum)