adventofcode/2023/day3/main.py

73 lines
1.8 KiB
Python
Raw Normal View History

def part1(file: str):
acc = []
with open(file) as f:
for line in f:
acc.append([(c, False) for c in line if c != "\n"])
for i1, r in enumerate(acc):
for i2, c in enumerate(r):
if not c[0].isdigit():
continue
check = False
def checker(a: int, b: int, check: bool):
# If already true
if check:
return True
# Sanity check
if a < 0 or len(acc) <= a:
return check
if b < 0 or len(acc[a]) <= b:
return check
# Adjacency check
it = acc[a][b][0]
if not it.isdigit() and not it == ".":
return True
return False
# Coordinates
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
check = checker(i1 + i, i2 + j, check)
if check:
acc[i1][i2] = (c[0], True)
# Find problems
buffer = ""
res = 0
for lines in acc:
test = False
for i, (c, t) in enumerate(lines):
if c.isdigit():
buffer += c
if t:
test = True
# End of number
if not c.isdigit() or i + 1 >= len(lines):
if len(buffer) > 0:
if test:
res += int(buffer)
test = False
buffer = ""
return res
""" def part2(file: str):
pass """
if __name__ == "__main__":
assert part1("example.txt") == 4361
print(part1("input.txt"))
""" assert part2("example.txt") == 2286
print(part2("input.txt")) """