summaryrefslogtreecommitdiff
path: root/2023/day03/solve.py
diff options
context:
space:
mode:
authorBotond Hende <nettingman@gmail.com>2024-12-11 10:18:23 +0100
committerBotond Hende <nettingman@gmail.com>2024-12-11 10:18:23 +0100
commit0a5c1f77d01fc0bd166494787f24562e2fd3a9e9 (patch)
tree99b0d38ef86653b6ff4aae26381ebdf0895f829d /2023/day03/solve.py
parentcbf5c348db4a693b15e455a23e07072587edf4b0 (diff)
renamed day folders to two digit format
Diffstat (limited to '2023/day03/solve.py')
-rw-r--r--2023/day03/solve.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/2023/day03/solve.py b/2023/day03/solve.py
new file mode 100644
index 0000000..bc84dc0
--- /dev/null
+++ b/2023/day03/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)
+