summaryrefslogtreecommitdiff
path: root/2023/day3/solve.py
blob: bc84dc0b8ceb3334723810ac121f3fed5dfc243f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from typing import List

def is_part_number(lines:List[str], column_count: int, row_pos: int, column_start: int, column_end: int) -> bool:
    min_column = max(column_start - 1, 0)
    min_row = max(row_pos - 1, 0)
    max_column = min(column_end + 1, column_count - 1)
    max_row = min(row_pos + 1, len(lines) - 1)

    for row_idx in range(min_row, max_row + 1):
        for col_idx in range(min_column, max_column + 1):
            char = lines[row_idx][col_idx]
            if char != "." and not char.isdigit():
                return True

    return False

def add_if_part_number(result: int, lines:List[str], column_count: int, row_pos: int, column_start: int, column_end: int) -> int:
    if is_part_number(lines, column_count, row_pos, column_start, column_end):
        result += int(lines[row_pos][column_start:column_end + 1])

    return result


data = []
with open("input") as f:
    for line in f.readlines():
        data.append(line.strip())

result = 0

columns = len(data[0])
for row_idx, line in enumerate(data):
    number_start_idx = -1
    for ii in range(columns):
        if line[ii].isdigit():
            if number_start_idx == -1:
                number_start_idx = ii
        elif number_start_idx != -1:
            result = add_if_part_number(result, data, columns, row_idx, number_start_idx, ii - 1)
            number_start_idx = -1

    if number_start_idx != -1:
        result = add_if_part_number(result, data, columns, row_idx, number_start_idx, columns - 1)

print(result)