2021-12-08 01:40:17 +00:00
|
|
|
with open("input.txt") as f:
|
2021-12-08 05:41:35 +00:00
|
|
|
crabs = [int(x) for x in f.read().split(',')]
|
2021-12-08 01:40:17 +00:00
|
|
|
|
|
|
|
from statistics import median, mean
|
|
|
|
from math import floor, ceil
|
|
|
|
|
|
|
|
def part1(crabs):
|
2021-12-08 05:41:35 +00:00
|
|
|
m = int(median(crabs)) # the median is the midpoint
|
|
|
|
offsets = [abs(x-m) for x in crabs] # that will be used to calculate simple cost.
|
|
|
|
return sum(offsets)
|
2021-12-08 01:40:17 +00:00
|
|
|
|
|
|
|
print(part1(crabs))
|
|
|
|
|
|
|
|
def part2(crabs):
|
2021-12-08 05:41:35 +00:00
|
|
|
def cost(d):
|
|
|
|
return d*(d+1)//2 # sum of successive integers = triangle numbers.
|
|
|
|
# because the mean is not an integer,
|
|
|
|
m1 = floor(mean(crabs)) # we might need the floor,
|
|
|
|
m2 = ceil(mean(crabs)) # or we might need the ceiling.
|
|
|
|
fuel1 = [cost(abs(x-m1)) for x in crabs] # we calculate both costs
|
|
|
|
fuel2 = [cost(abs(x-m2)) for x in crabs] # because it could be either one.
|
|
|
|
return min([sum(fuel1), sum(fuel2)]) # just take the lesser of the two.
|
2021-12-08 01:40:17 +00:00
|
|
|
|
|
|
|
print(part2(crabs))
|