add better day 7

This commit is contained in:
dave 2021-12-06 21:35:49 -08:00
parent d83cc7626f
commit f700df5b0a

37
7/b_better.py Normal file
View File

@ -0,0 +1,37 @@
from collections import defaultdict
with open("input.txt") as f:
all_crabs = [int(i) for i in f.read().strip().split(",")]
# group all crabs by starting position
crabs = defaultdict(int)
for crab in all_crabs:
crabs[crab] += 1
crabs = dict(crabs)
tries = []
# pre-calcuate crab movement costs
crab_cost = []
cost = 0
for i in range(0, max(all_crabs) + 1):
cost = cost + i
crab_cost.append(cost)
# apparently the equation `v = k * (k+1) / 2` is equivalent to the list
# generated above, however, this approach using a pre-computed list is 10-15%
# faster in my testing.
for i in range(min(all_crabs), max(all_crabs) + 1):
moves = 0
for crab, count in crabs.items():
more = crab_cost[abs(i - crab)] * count
moves += more
tries.append((i, moves, ))
tries.sort(key=lambda x: x[1])
print(tries[0][1])