zet-8-aoc-2021-07.md (2658B)
1 --- 2 title: 'Zettelkasten #8: Solution in D for Advent of Code 2021, Day 7' 3 date: '2021-12-17T22:25:00+01:00' 4 tags: ['zettelkasten', 'zet', 'dlang', 'aoc', 'aoc2021', 'adventofcode'] 5 description: "This post describes my solution in the D programming language for 6 the 7th puzzle of the Advent of Code 2021." 7 --- 8 9 ## The challenge 10 11 > A giant whale has decided your submarine is its next meal, and it's much 12 > faster than you are. There's nowhere to run! 13 > 14 > Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep 15 > for them otherwise) zooms in to rescue you! They seem to be preparing to 16 > blast a hole in the ocean floor; sensors indicate a massive underground cave 17 > system just beyond where they're aiming! 18 > 19 > The crab submarines all need to be aligned before they'll have enough power 20 > to blast a large enough hole for your submarine to get through. However, it 21 > doesn't look like they'll be aligned before the whale catches you! Maybe you 22 > can help? 23 > 24 > There's one major catch - crab submarines can only move horizontally. 25 > 26 > You quickly make a list of the horizontal position of each crab (your puzzle 27 > input). Crab submarines have limited fuel, so you need to find a way to make 28 > all of their horizontal positions match while requiring them to spend as 29 > little fuel as possible. 30 > 31 > [...] 32 > 33 > Determine the horizontal position that the crabs can align to using the least 34 > fuel possible. How much fuel must they spend to align to that position? 35 36 You can read the challenge more in depth, 37 [here](https://adventofcode.com/2021/day/7). 38 39 ## Part 1 40 41 ### Full solution 42 43 ```d 44 auto input = stdin.byLineCopy().front.splitter(",").map!(to!long); // input 45 input.map!(a => input.map!(b => abs(a-b)).sum).minElement.writeln; // calculate costs 46 ``` 47 48 ## Part 2 49 50 > The crabs don't seem interested in your proposed solution. Perhaps you 51 > misunderstand crab engineering? 52 > 53 > As it turns out, crab submarine engines don't burn fuel at a constant rate. 54 > Instead, each change of 1 step in horizontal position costs 1 more unit of 55 > fuel than the last: the first step costs 1, the second step costs 2, the 56 > third step costs 3, and so on. 57 > 58 > [...] 59 > 60 > Determine the horizontal position that the crabs can align to using the least 61 > fuel possible so they can make you an escape route! How much fuel must they 62 > spend to align to that position? 63 64 ### Full solution 65 66 ```d 67 auto input = stdin.byLineCopy().front.splitter(",").map!(to!long).array; // input 68 iota(input.maxElement).map!(a => input // iter 0 to max element 69 .map!(b => abs(a-b)*(abs(a-b)+1)/2).sum).minElement.writeln; // calculate costs 70 ```