advent_of_code/2023/3/3.py

83 lines
2.8 KiB
Python
Raw Normal View History

2023-12-04 03:06:27 +01:00
#!/usr/bin/env python
# 2023 - Advent Of Code 3
# file = 'input_example.txt'
file = 'input.txt'
def is_num(char):
if '0' <= char <= '9':
return True
return False
def parse_num(y, x):
pos = x
# print(f'begin pos: {pos}')
while pos > 0 and is_num(input_lines[y][pos-1]):
pos -= 1
# print(f'begin pos: {pos}')
n = ""
while pos < len(input_lines[y]) and is_num(input_lines[y][pos]):
n += input_lines[y][pos]
pos += 1
print(f'num: {int(n)}')
return int(n), pos
accum = 0
# pylint: disable=consider-using-with
input_lines = [line.strip('\n') for line in open(file, encoding="utf-8")]
# print(input_lines[y][x])
for linenum, line in enumerate(input_lines):
last_pos = 0
for charnum, c in enumerate(line):
if c != '.' and c < '0' or c > '9':
print(f'found {c} at {charnum},{linenum}')
if linenum > 0 and charnum > 0:
if is_num(input_lines[linenum-1][charnum-1]):
# print('7')
number, last_pos = parse_num(linenum-1, charnum-1)
accum += number
if linenum > 0 and last_pos < charnum:
if is_num(input_lines[linenum-1][charnum]):
# print('8')
number, last_pos = parse_num(linenum-1, charnum)
accum += number
if last_pos < charnum+1:
if is_num(input_lines[linenum-1][charnum+1]):
# print('9')
number, last_pos = parse_num(linenum-1, charnum+1)
accum += number
last_pos = 0
if charnum > 0:
if is_num(line[charnum-1]):
# print('4')
number, last_pos = parse_num(linenum, charnum-1)
accum += number
if is_num(line[charnum+1]):
# print('6')
number, last_pos = parse_num(linenum, charnum+1)
accum += number
last_pos = 0
if linenum < len(input_lines) and last_pos < charnum:
if is_num(input_lines[linenum+1][charnum-1]):
# print('1')
number, last_pos = parse_num(linenum+1, charnum-1)
accum += number
if last_pos < charnum:
if is_num(input_lines[linenum+1][charnum]):
# print('2')
number, last_pos = parse_num(linenum+1, charnum)
accum += number
if linenum < len(input_lines) and last_pos < charnum+1:
if is_num(input_lines[linenum+1][charnum+1]):
# print('3')
number, last_pos = parse_num(linenum+1, charnum+1)
accum += number
print(f"sum: {accum}")