day06 - revised

This commit is contained in:
Stefan Harmuth 2025-12-06 09:06:56 +01:00
parent e1f076a24f
commit 3b428360df

View File

@ -1,3 +1,5 @@
from collections import defaultdict
from tools.aoc import AOCDay from tools.aoc import AOCDay
from tools.math import mul from tools.math import mul
from typing import Any from typing import Any
@ -15,53 +17,48 @@ class Day(AOCDay):
] ]
] ]
def parse_input(self) -> list[tuple[list[int], int]]: def parse_input(self, part2: bool = False):
p = [l.split() for l in self.getInput()]
l = len(p[0])
r = []
for x in range(l):
r.append([y[x] for y in p])
return [(list(map(int, x[:-1])), x[-1]) for x in r]
def part1(self) -> Any:
ans = 0
for numbers, op in self.parse_input():
if op == '+':
ans += sum(numbers)
else:
ans += mul(numbers)
return ans
def part2(self) -> Any:
lines = self.getInput() lines = self.getInput()
ops = lines[-1].split() ops = lines[-1].split()
l = max(len(x) for x in lines)
rotated = [] ret = defaultdict(list)
for i in range(l): if not part2:
rotated.append("".join(x[i] if len(x) > i else " " for x in lines[:-1])) for line in lines[:-1]:
for i, num in enumerate(map(int, line.split())):
ret[i].append(num)
else:
rotated = defaultdict(str)
for line in lines[:-1]:
for i, c in enumerate(line):
rotated[i] += c
i = 0 i = 0
ans = 0 for _, line in sorted(rotated.items()):
total = 0 if ops[0] == '+' else 1 if line.strip():
for n in rotated: ret[i].append(int(line))
if not n.strip():
ans += total
i += 1
total = 0 if ops[i] == '+' else 1
continue
if ops[i] == '+':
total += int(n)
else: else:
total *= int(n) i += 1
ans += total return [x for _, x in sorted(ret.items())], ops
def calc(self, part2: bool = False) -> int:
ans = 0
numbers, ops = self.parse_input(part2)
for i, nums in enumerate(numbers):
if ops[i] == '+':
ans += sum(nums)
else:
ans += mul(nums)
return ans return ans
def part1(self) -> Any:
return self.calc()
def part2(self) -> Any:
return self.calc(part2=True)
if __name__ == '__main__': if __name__ == '__main__':
day = Day(2025, 6) day = Day(2025, 6)