Files
advent-of-code/2025/day06/part2.py

76 lines
2.8 KiB
Python

input = """123 328 51 64
45 64 387 23
6 98 215 314
* + * + """
with open("input.txt", "r") as file:
input = file.read()
operators = input.splitlines()[-1]
numbers = input.splitlines()[:-1]
# определяем начальные позиции операторов
start_positions = []
# проходим по строке операторов и записываем индексы всех непробельных символов
for index, char in enumerate(operators):
if char != ' ':
start_positions.append(index)
print(f"Стартовые позиции для каждой колонки: {start_positions}")
space_between = operators.replace("*","|").replace("+","|").split("|")[1:]
operators = operators.split()
# считаю количество символов для каждого элемента в списке
space_dig = []
for i in space_between:
space_dig.append(len(i))
#добавляем для последнего элемента в списке +1, потому что он не учитывается
space_dig[-1] = space_dig[-1] + 1
print(f"Количество символов для каждой строки: {space_dig}")
temp_data = []
for row in numbers:
row_data = []
for col_index, start_pos in enumerate(start_positions):
if col_index + 1 < len(start_positions):
end_pos = start_positions[col_index + 1]
cell_value = row[start_pos:end_pos]
else:
cell_value = row[start_pos:]
row_data.append(cell_value[:space_dig[col_index]])
temp_data.append(row_data)
result_data = [['' for __ in range(len(numbers))] for _ in range(len(space_dig))]
print(f"количество строк чисел в массиве: {len(numbers)}, количество чисел в строке: {len(space_dig)}")
# print("="*100)
# print(result_data)
print(space_dig)
for i, row in enumerate(temp_data):
print(f"Строчка {i+1}: {row}, операторы: {operators}, сколько элементов в каждой колонке: {space_dig[i]}")
for ii, r in enumerate(row):
for y in range(space_dig[ii]):
# print(y, space_dig[i])
result_data[ii][y] += r[y]
print(result_data)
# [['1 ','24 ', '356'], ['369', '248', '8 '], [' 32', '581', '175'], ['623', '431', ' 4']]
new_result = [[] for _ in range(len(space_dig))]
count = 0
for row, op in zip(result_data, operators):
temp = int(row[0])
for i in row[1:]:
if i != "":
if op == "*":
temp *= int(i)
elif op == "+":
temp += int(i)
new_result[count] = temp
count += 1
# print(new_result)
count_new = 0
for row in new_result:
count_new += row
print(new_result)
print(count_new)