summaryrefslogtreecommitdiff
path: root/2023/day3/solve.py
diff options
context:
space:
mode:
Diffstat (limited to '2023/day3/solve.py')
-rw-r--r--2023/day3/solve.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/2023/day3/solve.py b/2023/day3/solve.py
new file mode 100644
index 0000000..bc84dc0
--- /dev/null
+++ b/2023/day3/solve.py
@@ -0,0 +1,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)
+