Day 6: Part 2

This commit is contained in:
2025-12-07 17:38:21 +01:00
parent 07abb29dd5
commit 39c894486f

View File

@@ -1,7 +1,7 @@
# ========== PART 1 ==========
with open("day6/input.txt") as file: with open("day6/input.txt") as file:
lines = file.readlines() lines = file.readlines()
lines = [line.strip("\n").split() for line in lines] lines = [line.strip("\n").split() for line in lines]
for i in range(4): for i in range(4):
lines[i] = [int(number) for number in lines[i]] lines[i] = [int(number) for number in lines[i]]
@@ -18,7 +18,47 @@ for i in range(lineLen):
else: else:
print("ohoh ein Fehler") print("ohoh ein Fehler")
newGrandTotal = 0 # ========== PART 2 ==========
# Part 2 with open("day6/input.txt") as file:
raw_lines = [line.rstrip('\n') for line in file.readlines()]
print(f"Part 1: {grandTotal}\n\rPart 2: {newGrandTotal}") max_width = max(len(line) for line in raw_lines)
grid = [list(line.ljust(max_width)) for line in raw_lines]
num_rows = len(grid) - 1 # Number of rows with digits
op_row = len(grid) - 1 # Index of the operator row
max_cols = max_width
newGrandTotal = 0
current_numbers = [] # Stores numbers for the current problem (read R->L)
for col in range(max_cols - 1, -1, -1):
number_digits = ""
for row in range(num_rows):
char = grid[row][col]
if char.isdigit():
number_digits += char
operator = grid[op_row][col]
if operator == '+' or operator == '*':
if number_digits:
current_numbers.insert(0, int(number_digits)) # Prepend, as we are reading R->L
if not current_numbers:
continue
result = current_numbers[0]
if operator == '*':
for num in current_numbers[1:]:
result *= num
elif operator == '+':
for num in current_numbers[1:]:
result += num
newGrandTotal += result
current_numbers = []
elif number_digits:
current_numbers.insert(0, int(number_digits))
print(f"Part 1: {grandTotal}\nPart 2: {newGrandTotal}")