aoc2021/day07.py
Stefan Harmuth 4a45434585 day07
2021-12-07 06:12:44 +01:00

47 lines
1.0 KiB
Python

from functools import cache
from aoc import AOCDay
import math
from typing import Any
@cache
def getFuelForSteps(steps: int) -> int:
return int(steps * (steps + 1) / 2)
def getFuelUse(crabs, pos, exp=False):
fuel = 0
for c in crabs:
if exp:
fuel += getFuelForSteps(abs(pos - c))
else:
fuel += abs(pos - c)
return fuel
class Day(AOCDay):
test_solutions_p1 = [37]
test_solutions_p2 = [168]
def part1(self) -> Any:
crabs = self.getInputAsArraySplit(",", int)
minFuel = math.inf
for pos in range(min(crabs), max(crabs) + 1):
fuel = getFuelUse(crabs, pos)
if fuel < minFuel:
minFuel = fuel
return minFuel
def part2(self) -> Any:
crabs = self.getInputAsArraySplit(",", int)
minFuel = math.inf
for pos in range(min(crabs), max(crabs) + 1):
fuel = getFuelUse(crabs, pos, exp=True)
if fuel < minFuel:
minFuel = fuel
return minFuel