AdventOfCode/2023/day3/part1/part1.py

92 lines
2.7 KiB
Python

#!/bin/python3
import re
import sys
from pprint import pprint
input_f = sys.argv[1]
count = 0
arr = []
with open(input_f) as file:
for line in file:
arr.append(list(line.lstrip().rstrip()))
pprint(arr)
X=len(arr[0])
Y=len(arr)
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
for y2 in range(y-1, y+2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
(0 <= x2 < X) and
(0 <= y2 < Y))]
checked = []
numbers = []
print(len(arr))
print(len(arr[0]))
def find_num(n,m):
print("Looking at " + arr[m[0]][m[1]] + " ",end="")
print(m)
#print(n)
for i in n:
#print(i)
if arr[i[0]][i[1]].isdigit() and i not in checked:
#print(arr[i[0]][i[1]])
ctmp = 1
left=False
right=False
num = str(arr[i[0]][i[1]])
checked.append(i)
while left == False or right == False:
while arr[i[0]][i[1]-ctmp].isdigit() and (i[0],i[1]-ctmp) not in checked:
#print("checking " + str((i[0],i[1]-ctmp)) )
checked.append((i[0],i[1]-ctmp))
#print("First neighbor ",end="")
#print(arr[i[0]][i[1]-ctmp])
num = str(arr[i[0]][i[1]-ctmp]) + num
ctmp = ctmp + 1
#print("Found ",end="")
left = True
ctmp = 1
#print(i[1]+ctmp)
#print(len(arr))
#print(len(arr[0]))
#print(arr[i[0]][i[1]+ctmp])
while i[1]+ctmp < len(arr) and arr[i[0]][i[1]+ctmp].isdigit() and (i[0],i[1]+ctmp) not in checked:
#print("First neighbor ",end="")
checked.append((i[0],i[1]+ctmp))
#print(arr[i[0]][i[1]+ctmp])
num = num + str(arr[i[0]][i[1]+ctmp])
ctmp = ctmp + 1
right = True
#print(arr[i[0]][i[1]-ctmp])
#print("checked ", end="")
#print(checked)
#print(num)
numbers.append(int(num))
#print(i)
#print(i[0])
#print(i[1]-1)
#print(arr[i[0]][i[1]-1])
#print()
#print(numbers)
sym = ()
for idx,i in enumerate(arr):
for jdx,j in enumerate(i):
tmp = arr[idx][jdx]
if tmp.isdigit() == False and tmp != '.':
#print(tmp + " (" + str(idx) + "," + str(jdx) + ")")
n = neighbors(idx,jdx)
sym = (idx,jdx)
find_num(n,sym)
print(sum(numbers))