1+ from statistics import median
12from typing import List
23
34from adventofcode .util .exceptions import SolutionNotFoundException
45from adventofcode .util .helpers import solution_timer
56from adventofcode .util .input_helpers import get_input_for_day
7+ from adventofcode .util .math_helpers import mean_floor , mean_ceil , gaussian_sum
68
79
810def get_crabs (input_data : List [str ]) -> List [int ]:
@@ -18,6 +20,34 @@ def move_to_position(crabs: List[int], position: int) -> int:
1820 return fuel
1921
2022
23+ def get_least_amount_of_fuel (crabs : List [int ]) -> int :
24+ return move_to_position (crabs , int (median (crabs )))
25+
26+
27+ def get_least_amount_of_fuel_part_two (crabs : List [int ]) -> int :
28+ crabs .sort ()
29+ mean_crabs_floor = mean_floor (crabs )
30+ mean_crabs_ceil = mean_ceil (crabs )
31+
32+ return min (
33+ sum (gaussian_sum (abs (crab - mean_crabs_floor )) for crab in crabs ),
34+ sum (gaussian_sum (abs (crab - mean_crabs_ceil )) for crab in crabs ),
35+ )
36+
37+
38+ def get_least_amount_of_fuel_part_two_slower (crabs : List [int ]) -> int :
39+ crabs .sort ()
40+ mid = crabs [len (crabs ) // 2 ]
41+
42+ fuel = sum (gaussian_sum (abs (crab - mid )) for crab in crabs )
43+
44+ for position in range (min (crabs [mid :]), max (crabs ) + 1 ):
45+ position_fuel = min (fuel , sum (gaussian_sum (abs (crab - position )) for crab in crabs ))
46+ fuel = min (fuel , position_fuel )
47+
48+ return fuel
49+
50+
2151def try_all_positions (crabs : List [int ]) -> int :
2252 fuel = int (1e10 )
2353 crabs .sort ()
@@ -36,7 +66,7 @@ def try_all_positions(crabs: List[int]) -> int:
3666@solution_timer (2021 , 7 , 1 )
3767def part_one (input_data : List [str ]):
3868 crabs = get_crabs (input_data )
39- answer = try_all_positions (crabs )
69+ answer = get_least_amount_of_fuel (crabs )
4070
4171 if not answer :
4272 raise SolutionNotFoundException (2021 , 7 , 1 )
@@ -46,7 +76,8 @@ def part_one(input_data: List[str]):
4676
4777@solution_timer (2021 , 7 , 2 )
4878def part_two (input_data : List [str ]):
49- answer = ...
79+ crabs = get_crabs (input_data )
80+ answer = get_least_amount_of_fuel_part_two (crabs )
5081
5182 if not answer :
5283 raise SolutionNotFoundException (2021 , 7 , 2 )
0 commit comments