diff --git a/7/b_better.py b/7/b_better.py new file mode 100644 index 0000000..feb4a60 --- /dev/null +++ b/7/b_better.py @@ -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])