Advent Of Code 2021 - Day 7
On Day 7 we're being attacked by a giant whale. Luckily, there are a bunch of carbs in tiny submarines there to help us. The crabs do need some help in getting organized though, and that's our task.
The crabs needs to line up in the same horizontal ...
markestedt.hashnode.dev3 min read
You can calculate the triangle number of Math.abs(crab - i) instead of summing a range from 1 to Math.abs(crab - i). It would look something like this:
var positionCost = crabs.Select(crab => { var dist = Math.abs(crab - i); return dist * (dist + 1) / 2; }).Sum();It gives the same answer and it is a lot faster. I found this out after reading your post. Thanks for posting! It helped a lot!