generated from public/aoc_template
day06 - revised
This commit is contained in:
parent
e1f076a24f
commit
3b428360df
73
day06.py
73
day06.py
@ -1,3 +1,5 @@
|
||||
from collections import defaultdict
|
||||
|
||||
from tools.aoc import AOCDay
|
||||
from tools.math import mul
|
||||
from typing import Any
|
||||
@ -15,53 +17,48 @@ class Day(AOCDay):
|
||||
]
|
||||
]
|
||||
|
||||
def parse_input(self) -> list[tuple[list[int], int]]:
|
||||
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:
|
||||
def parse_input(self, part2: bool = False):
|
||||
lines = self.getInput()
|
||||
ops = lines[-1].split()
|
||||
l = max(len(x) for x in lines)
|
||||
rotated = []
|
||||
for i in range(l):
|
||||
rotated.append("".join(x[i] if len(x) > i else " " for x in lines[:-1]))
|
||||
|
||||
ret = defaultdict(list)
|
||||
if not part2:
|
||||
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
|
||||
ans = 0
|
||||
total = 0 if ops[0] == '+' else 1
|
||||
for n in rotated:
|
||||
if not n.strip():
|
||||
ans += total
|
||||
i += 1
|
||||
total = 0 if ops[i] == '+' else 1
|
||||
continue
|
||||
|
||||
if ops[i] == '+':
|
||||
total += int(n)
|
||||
for _, line in sorted(rotated.items()):
|
||||
if line.strip():
|
||||
ret[i].append(int(line))
|
||||
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
|
||||
|
||||
def part1(self) -> Any:
|
||||
return self.calc()
|
||||
|
||||
def part2(self) -> Any:
|
||||
return self.calc(part2=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
day = Day(2025, 6)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user