|
| 1 | +# wrong answer, but seems to work as expected up to line 3 (line_idx=2) number: 667 (number_idx: 57) |
| 2 | +# every line in the "engine schematic" (-> the puzzle input) has 141 characters |
| 3 | +LINE_LENGTH = 141 |
| 4 | +# the "engine schematic" has 140 lines |
| 5 | +NUMBER_OF_LINES = 140 |
| 6 | + |
| 7 | +input_lines = [] |
| 8 | + |
| 9 | + |
| 10 | +def is_part_number(line_idx: int, number_idx: int, number_length: int): |
| 11 | + if number_idx != 0: |
| 12 | + if is_part_marker(input_lines[line_idx][number_idx - 1]): |
| 13 | + return True |
| 14 | + if line_idx != 0: |
| 15 | + if is_part_marker(input_lines[line_idx - 1][number_idx - 1]): |
| 16 | + return True |
| 17 | + if line_idx != NUMBER_OF_LINES - 1: |
| 18 | + if is_part_marker(input_lines[line_idx + 1][number_idx - 1]): |
| 19 | + return True |
| 20 | + if number_idx + number_length != LINE_LENGTH - 1: |
| 21 | + if is_part_marker(input_lines[line_idx][number_idx + number_length]): |
| 22 | + return True |
| 23 | + if line_idx != 0: |
| 24 | + if is_part_marker(input_lines[line_idx - 1][number_idx + number_length]): |
| 25 | + return True |
| 26 | + if line_idx != NUMBER_OF_LINES - 1: |
| 27 | + if is_part_marker(input_lines[line_idx + 1][number_idx + number_length]): |
| 28 | + return True |
| 29 | + if line_idx != 0: |
| 30 | + for idx in range(number_idx, number_idx + number_length): |
| 31 | + if is_part_marker(input_lines[line_idx - 1][idx]): |
| 32 | + return True |
| 33 | + if line_idx != NUMBER_OF_LINES - 1: |
| 34 | + for idx in range(number_idx, number_idx + number_length): |
| 35 | + if is_part_marker(input_lines[line_idx + 1][idx]): |
| 36 | + return True |
| 37 | + |
| 38 | + return False |
| 39 | + |
| 40 | + |
| 41 | +# Part Marker refers all symbols except the '.'. |
| 42 | +# As stated in the puzzle any number that is in any way adjacent to one of these symbols is a part number. |
| 43 | +def is_part_marker(adjacent_char: str): |
| 44 | + return not adjacent_char.isdigit() and adjacent_char != "." |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + with open("day3_input.txt", "r") as input_file: |
| 49 | + input_string = input_file.read() |
| 50 | + |
| 51 | + global input_lines |
| 52 | + input_lines = input_string.splitlines() |
| 53 | + part_numbers_sum: int = 0 |
| 54 | + |
| 55 | + for line_idx, line in enumerate(input_lines): |
| 56 | + number: str = "" |
| 57 | + number_idx: int | None = None |
| 58 | + for char_idx, char in enumerate(line): |
| 59 | + if char.isdigit(): |
| 60 | + number += char |
| 61 | + if not number_idx: |
| 62 | + number_idx = char_idx |
| 63 | + elif number_idx: |
| 64 | + if is_part_number(line_idx, number_idx, len(number)): |
| 65 | + part_numbers_sum += int(number) |
| 66 | + number = "" |
| 67 | + number_idx = None |
| 68 | + |
| 69 | + print("Sum of part numbers:", part_numbers_sum) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + main() |
0 commit comments