diff --git a/puzzles/day07.py b/puzzles/day07.py index 513ff43..36301ce 100644 --- a/puzzles/day07.py +++ b/puzzles/day07.py @@ -17,22 +17,37 @@ class AlignCrabSubs: def __init__(self, positions: List[int]) -> None: self.positions = positions - def calc_least_fuel(self) -> int: - target = median(self.positions) + def calc_fuel(self, pricey: bool = False) -> int: + if pricey: + fuel = None + for position in range(len(self.positions) + 1): + price = self.calc_fuel_pricey(position) + if fuel is None or fuel > price: + fuel = price + + return fuel + else: + return self.calc_fuel_simple(median(self.positions)) + + def calc_fuel_simple(self, target: int) -> int: + return int(sum(abs(num - target) for num in self.positions)) + + def calc_fuel_pricey(self, target: int) -> int: fuel = 0 for num in self.positions: - fuel += abs(num - target) - + num_range = abs(num - target) + 1 + fuel += sum(range(num_range)) return int(fuel) def part1(inputs: List[int]) -> int: subs = AlignCrabSubs(inputs) - return subs.calc_least_fuel() + return subs.calc_fuel() def part2(inputs: List[int]) -> int: - return False + subs = AlignCrabSubs(inputs) + return subs.calc_fuel(pricey=True) def parse(inputs: str) -> List[int]: diff --git a/puzzles/test_day07.py b/puzzles/test_day07.py index b699ed6..af01a17 100644 --- a/puzzles/test_day07.py +++ b/puzzles/test_day07.py @@ -20,15 +20,13 @@ def test_example1(example_data): assert aoc.part1(example_data) == 37 -@pytest.mark.skip(reason="Not implemented") def test_example2(example_data): - assert aoc.part2(example_data) == ... + assert aoc.part2(example_data) == 168 def test_part1(day07_data): assert aoc.part1(day07_data) == 343441 -@pytest.mark.skip(reason="Not implemented") def test_part2(day07_data): - assert aoc.part2(day07_data) == ... + assert aoc.part2(day07_data) == 98925151