87 lines
3.1 KiB
Python
87 lines
3.1 KiB
Python
#!/usr/bin/env python
|
|
# 2023 - Advent Of Code 3 - part 2
|
|
|
|
# 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 == '*':
|
|
part_found = []
|
|
print(f'found gear at {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)
|
|
part_found.append(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)
|
|
part_found.append(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)
|
|
part_found.append(number)
|
|
last_pos = 0
|
|
if charnum > 0:
|
|
if is_num(line[charnum-1]):
|
|
# print('4')
|
|
number, last_pos = parse_num(linenum, charnum-1)
|
|
part_found.append(number)
|
|
if is_num(line[charnum+1]):
|
|
# print('6')
|
|
number, last_pos = parse_num(linenum, charnum+1)
|
|
part_found.append(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)
|
|
part_found.append(number)
|
|
if last_pos < charnum:
|
|
if is_num(input_lines[linenum+1][charnum]):
|
|
# print('2')
|
|
number, last_pos = parse_num(linenum+1, charnum)
|
|
part_found.append(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)
|
|
part_found.append(number)
|
|
if len(part_found) == 2:
|
|
# gear_ratio = int(part_found[0]) + int(part_found[1])
|
|
# print(f'gear ratio {gear_ratio}')
|
|
accum += int(part_found[0]) * int(part_found[1])
|
|
|
|
|
|
print(f"sum: {accum}")
|