r/adventofcode • u/daggerdragon • Dec 07 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 7 Solutions -🎄-
--- Day 7: The Treachery of Whales ---
[Update @ 00:21]: Private leaderboard Personal statistics issues
- We're aware that
private leaderboardspersonal statistics are having issues and we're looking into it. - I will provide updates as I get more information.
- Please don't spam the subreddit/mods/Eric about it.
[Update @ 02:09]
AoC_Ops have identified the issue and are working on a resolution.
[Update @ 03:18]
- Eric is working on implementing a fix. It'll take a while, so check back later.
[Update @ 05:25] (thanks, /u/Aneurysm9!)
- We're back in business!
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - Format your code properly! How do I format code?
- The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:03:33, megathread unlocked!
96
Upvotes
8
u/JustinHuPrime Dec 07 '21
x86_64 assembly
Apparently people don't like to do these in assembly - I wonder why.
Part 1
Part one was solved by reading in all of the numbers, doing an in-place (unstable) quicksort, and then taking the median by averaging the two middle-most values.
Part 2
Part two was solved by reading in all of the numbers, and then doing a brute force search. This wasn't too bad, since I could heavily optimize the tight inner loops.
6
u/ephemient Dec 07 '21 edited Apr 24 '24
This space intentionally left blank.
6
u/AhegaoSuckingUrDick Dec 07 '21 edited Dec 08 '21
Hello everyone.
In the first part you just find the median and that's it.
The second part is a bit more interesting. Let's first find a precise answer, i.e., the value y that minimizes our loss function
L(y) = \sum (|y-x_i| + 1) |y-x_i| / 2. Now, take a derivativedL/dyand set it to zero. It'll give usy = mean(x) - (\sum sign(y - x_i)) / 2n. Since the answer lies between the minimum and the maximum, we know that0 < \sum sign(y - x_i) < n. Thus, y lies in the open interval(mean(x) - 0.5, mean(x) + 0.5), and eitherfloor(mean(x))orceil(mean(x))is the integral answer.edit: Since a lot of people seem to solve the problem without considering
ceil(mean(x)), it would fail for the input1,10,11,12.edit 2: Some reference OCaml implementation:
4
u/DFreiberg Dec 07 '21 edited Dec 07 '21
Mathematica, 51 / 95
It turns out that the sum of numbers from
1tonis not, in fact,n*(n-1)/2. It took me three seconds to realize what was wrong and fix it, and then another agonizing fifty-seven seconds to wait to resubmit.Interestingly, despite seemingly being the same complexity, part 1 takes 15 milliseconds to run while part 2 takes 2000 milliseconds. I'm not sure why.
Part 1:
Part 2:
[POEM]: The Crustacean Supplication
Crabs above whose sea we scuttle
Give us aid, and not rebuttal,
Danger comes, surpassing cuttle:
Blast a hole, and don't be subtle!
We've made friends with a crustacean
Stacking cups while on vacation,
After games of long duration:
Save us from this huge cetacean!
Whales are fast; too late we tracked them.
Bingo, too, does not distract them.
Submarines, like ours, attract them:
Save us, or they'll soon have snacked them!
Hurry, blast through sheet and shale!
Wale away, away from whale!
It's almost here! We must not fail!
Grant us weal lest we should wail!
4
u/sawyerwelden Dec 07 '21 edited Dec 07 '21
Bonus 1-liner
Julia (1014 / 1231) Median is faster but I wasn't sure of the syntax and the input is small
4
u/captainAwesomePants Dec 07 '21
Python (pretty bad) (not sure how bad because site is 500ing (!!) )
The version I submitted did the cost in a for loop because I forgot math. While it was running, I looked up the formula, but just as I finished plugging it in, the original version passed.
4
u/SuperSmurfen Dec 07 '21 edited Dec 07 '21
Rust (5141/2440)
Link to full solution
Not sure how fast I was, since the leaderboard is down, but it felt pretty fast. I think my solution is similar to most other people.
Itertools::minmaxis pretty useful here:Just remove the
gaussfor part 1.Edit: Apparently, I wasn't fast at all.
4
u/oantolin Dec 07 '21 edited Dec 07 '21
For part 1, I happened to know the median minimizes the sum. For part 2, I used SageMath's
find_local_minimumto find the minimum and just rounded that answer to the nearest integer:(SageMath is variant of Python ---really just Python with a preprocessor that adds a bit of syntax--- with an enormous collection of mathematical libraries.)
4
u/[deleted] Dec 07 '21 edited Dec 07 '21
If anyone is having trouble with the execution time in part 2 (or is just annoyed by it), I got my time down by using Gauss' sum equation.
sum of 1 to n = (n/2)*(1+n)
This got my python code execution time from about 20 seconds to 1 second.
edit: added solution
Python Solution:
4
u/naclmolecule Dec 07 '21 edited Dec 07 '21
Python
For part two, one can approximate the solution using gradient descent to minimize the number of guesses you need to make.
So, this was my solution:
4
u/jpn3to Dec 07 '21 edited Dec 07 '21
The problem asks us to minimize a cost. In the first part, the cost of position $p$ is proportional to the sum of distances from $p$ to all crabs. So, for a given position $p$, the cost is $\sum_x |x-p|$. The position that minimizes this cost is called the median, the well-known central tendency in statistics.
In Python,
For part 2, the cost is given by the n-th triangular number, T_n = n(n+1)/2. We can drop the 2 and say the cost at position $p$ is proportional to $\sum_x |x-p| (|x-p|+1)$ which has a very similar shape to $\sum_x (x-p)2$ the quadradic cost of the distance.
The statistic that minimizes the quadratic cost is the mean. Of course, the mean might not be an integer and is not the answer. But it will give a starting point to explore the minimal cost we need, which should be very near this value.
[edit] So to compute part 1
and for part 2, rounding the mean to integer provided my answer
4
u/snurre Dec 07 '21 edited Dec 08 '21
Kotlin
4
u/meMEGAMIND Dec 07 '21
Solution in Desmos Graphing Calculator
I took a couple days off, now working backwards from 7 to catch up.
Today's solution fried my desmos for some reason, so it's all commented right now. if you want to test it, just copy/paste those into equation lines.
3
u/Fluffy_Bag_6560 Dec 07 '21
Java, Server died so no position.
https://github.com/JariRoossien/AdventOfCode2021/blob/master/src/nl/jariroossien/aoc/days/Day07.java
3
u/fezzinate Dec 07 '21
Javascript: https://github.com/DanFessler/advent-of-code/tree/master/2021/07
Fun and easy. I'm a big fan of passing a function as a param to a single solver to handle the different parts when possible.
3
u/FruitdealerF Dec 07 '21 edited Dec 07 '21
Today I learned about triangle numbers. This one was really easy for me and I'm super happy with my Kotlin solution.
3
u/0x2c8 Dec 07 '21 edited Dec 07 '21
Python
solve.py
I tried both binary search and direct calculation.
The write-up for the calculation is here (PDF), extending upon this answer from Math StackExchange. It's not 100% formal, but I am fairly confident that it's correct.
If anyone has any suggestions, I'd greatly appreciate it.
3
u/apreche Dec 07 '21 edited Dec 08 '21
Python
Did it the straightforward way, as is my typical style. My part 1 solution is the same, only without the triangular number part.
3
u/prafster Dec 07 '21 edited Dec 08 '21
Julia
I wondered what the catch was today in part 1. I implemented a brute force method, which was not fast but sub-second. For part 2, I thought I'd need to memoize the calculation of the increasing fuel cost. But this turned out to not be required. I'm happy this was as straightforward as it appeared since I had little time.
The relevant functions are below but the full solution is on GitHub:
6
u/CCC_037 Dec 07 '21
Rockstar:
Part 1:
Part 2:
2
u/seligman99 Dec 07 '21 edited Dec 07 '21
Python 443 / 564 (..
the leaderboard is wonky right now, all better now)Be interesting to see better solutions than my brute force one
github
2
u/the_great_beelzebub Dec 07 '21
quickest submission i have made yet:
leaderboard/selfis a 500 at the moment but i was about ~1200/700python3:
2
u/sbguest Dec 07 '21
Javascript
Part 1 | Part 2
Nothing special, but I'm happy to finally hit the leaderboard for the first time this year (84th in part 2). Competition is getting stiff as this event keeps growing.
Part 2 has been rewritten to use triangular number formula to make it faster, but I couldn't call that one to mind while I was actually going for time, so it was for-loop city.
2
u/frontpageminus Dec 07 '21 edited Dec 07 '21
Ruby 1712/1304
paste
2
u/FqdingSky Dec 07 '21
c++
as soon as i submitted it told me 'internal server error' when i tried to access my personal leaderboard :/
for part 1 just remove the 'math()' function
2
u/yollotltam Dec 07 '21
PYTHON 3
2
u/Kermitnirmit Dec 07 '21
Python3 <1000 for both, 500ing so I can't see ranks...
Thank gauss for that triangular number formula. Super cool problem today that will thankfully let me sleep early tonight.
2
u/Kehvarl Dec 07 '21
Python ?/? Personal stats seem to be down for the moment. This took me about 25 minutes, which I feel could have been worse.
There's nothing really unusual about my approach, and I'm certain I could speed up part 2 significantly somehow. Still, that was interesting!
paste
2
u/nlowe_ Dec 07 '21 edited Dec 09 '21
Go, 3935/3923
Got a slow start today trying to parse the problem. I think I had yesterday's still stuck in my head because it took me a few times reading through before I got it, after that it was fairly easy. Cleaned up my part B after solving with our good old pal n*(n+1)/2.
Not quite sure how I did, seems like the leaderboards are having a sad. My private leaderboard seems to think I've only done one day. #HugOps to the AoC team!EDIT: Leaderboard is up!
2
u/[deleted] Dec 07 '21
Today was my personal best day, needed about half an hour.
[Part one](https://topaz.github.io/paste/#XQAAAQDMAAAAAAAAAAAxnIhFo9JuI0mU+VldtRuCXPE8sgV8Cfth70NBNYs5NTSB4o+O73vVEyInlqj2/vBkRUmZ4jkySfle4tyY2+7v1uJP99bj7WlqLqujFvX/A6NX4MkwBQpv6bPP4+dxKA1MrIELKorP7ixi5GHCh1QuHvi0M2DCI1c4vJs3wOiLIOknc9CquJ3JFY5k//ojPwA=)
[Part two](https://topaz.github.io/paste/#XQAAAQC9AAAAAAAAAAAyGUj/TwpvLh9LqSEzkO8BIQN5fGREUl8tRgjzv8sFZSRZ/UVlo0QBDZU3qra6RlVIuubLDDqz6JwxIPU80P1KBqWk4SaGSeXbJeHdyyZq/upXLODysLDFd03bejZvNLAXbkuT2IjBmSd8nqQGpIyIaeuU/GZhWNol5Nz7y7z/h11/AA==)
2
u/boynamedluke4 Dec 07 '21
golfed python solution part 2 ~10 min
import fileinputraw = [int(s) for s in str(fileinput.input()[0]).split(',')]print(min(sum([(abs(r - i) * (abs(r - i) + 1))//2 for r in raw]) for i in range(max(raw))))2
u/irudog Dec 07 '21 edited Dec 07 '21
My Ada solution: https://github.com/mytbk/advent_of_code/blob/main/2021/07/advent_07.adb
In part 2, I tried to find the best position of
f(x)=Sum(|x-a(i)|(|x-a(i)|+1)/2), and for the sorted lista(1 .. n)and x in[a(i),a(i+1)]f is a quadratic function and can find the minimum point.Update: my original code is wrong... The code is updated and it seems using the average value of
ais almost right.2
u/bilal-abraham Dec 07 '21 edited Dec 08 '21
JavaScript | 3796/2886
[part1, part2]
2
u/LtHummus Dec 07 '21
Scala
Another late start on this one because I was at a hockey game (rip Seattle Kraken :( )
2
u/Diarmuid_ Dec 07 '21
Setup
Part 1
Part2. I remembered the story about Gauss but had to work out the formula
2
u/ffmich_ Dec 07 '21 edited Dec 08 '21
JavaScript
Used median for the first part and arithmetic mean for the second
Part 1 and Part 2
2
u/No-Rip-3798 Dec 07 '21 edited Dec 08 '21
It was much too early to be clever, so here's my solution in Go using a binary search. Both parts are solved in
O(N*log(N)).2
u/pi55p00r Dec 07 '21 edited Dec 07 '21
R Rstats Day 7
Part1:
Make a df of all combinations and find minimum sum of displacements for each position
Part2:
Make a df of all combinations and find sum of integers in displacement using sum of integers formula
Edit:added language
2
u/[deleted] Dec 07 '21
Julia
ranges are really useful for the second part
2
u/d1sxeyes Dec 07 '21 edited Jul 21 '26
Redacted.
2
u/cggoebel Dec 07 '21 edited Dec 07 '21
Raku
2
u/Synedh Dec 07 '21
Python
Sloth now has a code file.
Brute force for each value in the range of input, get the minimal result. Back to sleep, tomorrow will be better.
For part 2,
sum(1, 2, ..., n) = sum(range(1, n+1)).2
u/_mattmc3_ Dec 07 '21
Fish shell
It's a little slow, but it works.
2
u/ceron257 Dec 07 '21 edited Dec 08 '21
Python solution: from statistics import median, mean
I'm not sure though if this will give the correct answer for all inputs. Does anyone else have a clue?
Is it maybe possible to prove this mathematically?
My reasoning for this solution was that with the median you will pick the position where the least amount of crabs would have to move at all while with the mean the least amount of crabs would have to move a greater distance.
2
u/[deleted] Dec 07 '21 edited Dec 07 '21
Python
Part 2 can probably be de-duplicated, but I'm too lazy to do it now.
I'd be interested to know why the
min(..., ...)is necessary, though. Simply rounding produces the correct solution with the example data and it feels weird that the value further (albeit only slightly) from the mean produces the lower solution. Is it just due to the distribution in my particular dataset?2
u/SirGuelph Dec 07 '21
Javascript
2
u/anh86 Dec 07 '21 edited Dec 07 '21
On first blush in part one, I thought that the average position would result in the lowest total fuel use and I initially wrote my program to move each crab there and compute the fuel. When that was wrong, I just rewrote it to brute force check each possible position and tell me the most fuel-efficient one. That worked but someone smarter than me tell me why the average position wouldn't necessarily to be the most efficient?
2
u/onsistems Dec 07 '21 edited Dec 08 '21
PHP, Part 1 and Part 2 solutions
2
u/Symbroson Dec 10 '21 edited Dec 12 '21
a day to relax - haskell
just replace cost1 and 2 for the different parts
2
u/cdaringe Dec 12 '21 edited Dec 13 '21
OCaml: https://github.com/cdaringe/aoc-2021/blob/main/day7/lib/day7.ml#L22
I cannot reason about why there is only one local minima. I can half intuit it, but I cannot put my finger on it.
F= sum of all crab fuel consumption(s)f= crab fuel consumptionp= crab positionp_i= ith crab positionp_t= target positionmin_p= a calculated constant,minimum (p_i .. p_n)min_x= a calculated constant,maximum (p_i .. p_n)Minimize F, where
F = Σ[i=min_p to i=max_p] triangle_cost(p_i - p_t)If someone can set my head straight, that'd be rad
2
u/ElGoorf Dec 15 '21 edited Dec 19 '21
JavaScript
I messed up. First I tried getting the mean average position to move all the crabs to, but that number was way off. So then I bisected my way to an answer, the whole time the back of my head confused about why the mean was wrong: https://github.com/ElGoorf/aoc2021/blob/main/07/01.js
Kind of kicking myself now seeing other people's answers and realizing I actually wanted the median, not the mean, but hey, here's a unique approach.
48
u/4HbQ Dec 07 '21 edited Dec 07 '21
Python, using the median (part 1) and the mean (part 2) of the crab locations. This way, there is no need to "search" for the optimal position:
The median works for part 1 because of the optimality property: it is the value with the lowest absolute distance to the data.
Unfortunately, this does not work for part 2, because the "distances" (measured in fuel consumption) are no longer linear: if you double the distance, you need more than double the fuel.
In fact, the distances are the triangle numbers, which are defined by n × (n+1) / 2. Because of the n2 in there, we know that the arithmetic mean
has the lowest total distance to the datais close to optimal.Update, thanks to /u/falarkys and /u/slogsworth123:
Assuming the mean is less than 0.5 from the best position, we simply check the two integers around the mean.
•
u/Aneurysm9 Dec 07 '21
[Update @ 05:25]
18
u/mcpower_ Dec 07 '21
Python, 1/42 - immediately recognised part 1, blanked at how to do part 2 until I realised the input is small.
Part 1:
Part 2:
14
u/leijurv Dec 07 '21 edited Dec 07 '21
Python, 2nd place (50 seconds!!!!), 68th place
Screen recording https://youtu.be/ozxNkb7d2tw
Part 1
Part 2
Important note: My part 2 is technically wrong. It only worked by luck. For example it fails on the sample input. A correct implementation would do
for dest in range(min(ll), max(ll)+1):.13
u/voidhawk42 Dec 07 '21 edited Dec 07 '21
APL, assuming that zero is always present in the input (seems safe):
EDIT: For a much, MUCH faster part 2, I remembered that you can use binomial coefficients instead:
EDIT2: And if we want to go even faster, we can use the median/average as some other solutions here have done:
This second solution runs in 2.5 ms on my machine, whereas my original solution runs in 800 ms, lol
16
u/emilhvitfeldt Dec 07 '21
R
The trick to this one is that the optimal horizontal position for part 1 is the median value of the input, and the optimal horizontal position for part 2 is mean (rounded down)
8
u/MichaelRosen9 Dec 07 '21
Julia
The median minimises the L1 norm of the distances (i.e. the fuel cost for part 1), and the mean minimises the L2 norm (sum of squared distances). The fuel cost for part 2 is
sum(dist*(dist+1)/2), i.e. the average of the L1 and L2 norms of the distances. We can reason that the best alignment position will be between the mean and the median, because when moving outside of that interval both the L1 and L2 norms will be increasing.8
u/r_so9 Dec 07 '21
F#
7
u/jaybosamiya Dec 07 '21
APL
7
u/relativistic-turtle Dec 07 '21
IntCode
(Note: assumes 1000 crabs in input)
Part 1: "Hmm, the optimal position should be given by taking the mean off all crab-positions and round to nearest integer... but I'm lazy. Let's just loop through every position and crab!"
Part 2: Same, and using 1+2+3+...+n = n*(n+1)/2
7
u/cocotoni Dec 07 '21
PowerShell
Parts 1 & 2
Part 1
Part 1 is the mathematical definition of geometric median, so we calculate it as such, in one dimensional space. I've used a generalised formula, but given the test numbers and real input numbers, I suspect that it can be optimised given that:
From there it's a simple matter of calculating the sum of distances from the median point.
Part 2
Given the test input it 'felt' that the point we are searching for is the arithmetic mean of all the positions. However, the mean can be rational, non integer, number (and is in the case of both test and my inputs), so we calculate separate results for ceiling and floor, and produce the lower result. Of course, here the fuel spent is the sum of integers from one to the distance between the crab and the mean point, which is calculated using the formula for triangle numbers.
7
u/Gravitar64 Dec 07 '21
Python 3, Part 1&2 in 1ms, pure Python
6
u/RandomGuyJCI Dec 07 '21 edited Dec 07 '21
Very simple to implement in APL!
6
u/aimor_ Dec 07 '21
MATLAB
6
u/flwyd Dec 07 '21
Raku, 3004 / 2778. The following (MIT-licensed) code is a code golf version of what I originally wrote.
6
u/piyushrungta Dec 07 '21 edited Dec 07 '21
Nim Lang
https://github.com/piyushrungta25/advent-of-code-2021/blob/master/day-07/main.nim
Looked at the input and figured out that the input is not large enough and can be brute forced for part1. Also played around with some values and got the right answer for part2 using floor(mean) but replaced with brute force solution since taking mean is not the right solution in every case.
Edit: seems like taking the median for part1 is the right way to do it, but not changing it since the brute force solutions is also good enough for the input.
Edit2: did some bench marking on my machine(i3-1005G1 @ 1.20GHz) with Hyperfine.
Code used -
6
u/jayfoad Dec 07 '21
Dyalog APL
6
u/__Abigail__ Dec 07 '21
Blog post The Treachery of Whales (Perl)
5
u/u794575248 Dec 07 '21 edited Dec 07 '21
J Language (an array programming language based primarily on APL)
5
u/Biggergig Dec 07 '21 edited Dec 07 '21
Python 66/>100
5
u/JoMartin23 Dec 07 '21
Common Lisp
brute force
5
u/entoros Dec 07 '21
Q
5
u/fmorel Dec 07 '21
C#. I always end up trying to use collection methods as much as possible at the end to see how short I can get it but still be somewhat readable.
5
u/gansanay Dec 07 '21 edited Dec 07 '21
Python 3
Part 1: median, Part 2: mean, and 1 + ... + k = k * (k + 1) / 2
EDIT/BEWARE : the floor of the mean isn't always the closest, for the example input it is the ceiling. Will look into it and fix this post
EDIT 2: fixed in the general case by using the min of the ceil and floor of the mean (which minimizes the "cumulative fuel" distance) -> see GitHub repo
The following was then wrong in the general case:
5
u/stevelosh Dec 07 '21
Common Lisp
https://github.com/sjl/advent/blob/master/src/2021/days/day-07.lisp
5
u/0rac1e Dec 07 '21 edited Dec 07 '21
Raku
Pulling in
medianandmeanfrom the Stats module.I did golf it a little. I tend to solve things with
mapand loops, then see what I can strip away.Part 2 was original written as: -
But what I like about my final golf is that - while there's
map'ing happening everywhere - the wordmapdoes not appear once.See my J translation here
Update
It seems I got lucky here, and my part 2 solution is incorrect for the sample input. I'm not sure if that means it also may be incorrect for different inputs. From other comments it seems I may need to take both the floor and ceiling, and pick the lowest.
For my penance, I will provide not 1, but 2 alternative solutions for part 2... each one more maptastic than the next.
5
u/Toanuvo Dec 07 '21
j solution
https://github.com/Toanuvo/Advent-of-code-2021/blob/main/J/day7.ijs
5
u/nutrecht Dec 07 '21
This one was very easy.
Day 7 in Kotlin
5
u/NutellaGod Dec 07 '21 edited Dec 07 '21
C#
i could probably refactor this to be one giant linq expression if i wanted to
Edit:
5
u/4HbQ Dec 07 '21 edited Dec 07 '21
Python, solution for both parts golfed down to
129110 bytes (hat tip to /u/AtomicShoelace):More readable version:
5
u/zniperr Dec 07 '21
python3:
5
u/Smylers Dec 07 '21
A plethora of Perl solutions — I just couldn't keep tweaking!
I realized part 1 would be at the median, because of an episode of Dara Ó Briain: School of Hard Sums where he was challenged by Marcus du Sautoy to work out the best meeting place for a group of friends in a 2D city grid:
A brute-force approach to part 2 wasn't as slow as I'd feared (about ⅓ of a second):
If I'm brute-forcing anyway, I may as well calculate part 1 at the same time. It took a while to work out how to combine the common parts —
zip_byturned out to be the answer, withmapcreating a 2-element array for each start position, containing the distance to travel and the triangular number of that distance, thenzip_byseparatelysum-ing all of the first elements and all of the second:Then, after realizing part 2 ends up at the mean position (which, I think, is what Dara Ó Briain incorrectly calculated for the simpler problem, failing to solve it with just maths, beaten by his comedian competitors who came up with the right answer by running round the city with a stopwatch), that becomes a simple variant on the median solution for part 1:
(Though I'm not entirely sure why it requires
intto always round down, rather than rounding to the nearest.)Anyway, having the median and mean solutions in 2 different files with mostly the same structure was bothering me; I wanted to combine the common parts. The parts just differ in the function for calculating the end point, and the cost calculations:
So let's iterate over those. But how? Rummaging through
List::AllUtils, I foundpairmapwould work, each part basically being a pair of functions:That works! But it isn't great that in the
pairmapblock the functions end up being named just$aand$b. What else is in there? There'sbundle_by, which passes in the pairs as args, so they can be named whatever we want:Is that better? That
2in there specifies iterating over the items that follow in groups of 2. What about grouping each part's definition with named hash keys? Then I can putList::AllUtilsdown and just useforeach:I couldn't decide which I like best, so I've ended up with a program which does all of them in turn, printing the answer for each part 3 times. And still running in ⅒ of the time of brute-forcing the answer for just part 2 once.
Any preferences?
5
u/WeirdFlex9000 Dec 07 '21
Part 2: algebraic solution
The whole day I was wondering if there's not some algebraic solution to this... Not having seen something in here, I finally decided to sit down and try to derive it myself. Disclaimer: I'm not a mathema(t|g)ician, so I struggled quite a bit with derivations of absolute values.
The formula I ended up with is: For a list
pof a total ofNcrab positions, the optimal position that uses the least fuel is:(sum(p) - N) / (N - 1).This actually seems to check out! With the regular loop solution, I get (for my numbers) the (accepted!) solution:
Now with my formula, I get:
So I actually managed to save 8 fuel over the accepted answer!!!
Obviously that's because it becomes a non-discrete solution. If we round, we end up with the same solution as with the loopy code.
Here's a solution in Python (part 2)
5
u/mediumcups Dec 07 '21
Excel
Solved using Excel's Solver program, which is an add-in that can be used to find an optimal value for a given function.
In both parts, we want to minimize the total fuel cost by picking a integer point p such that the sum of all individual fuel costs to that point p is minimal.
Therefore, set aside a cell to hold the value of p. Then calculate the individual costs for all 1000 crabs. Then sum them all up in a separate cell, X. X represents the total cost and we want to find the minimum value for this particular cell.
In the Solver add-in, select cell X as the objective function, and set it to find the minimum value.
Then set the cell containing the value for p to be the variable cell we want to change.
Add an Integer constraint for the cell containing the value for p, since we are only interested in integer solutions, then click solve.
4
u/rabuf Dec 07 '21
Common Lisp
I thought I'd have to optimize it for part 2, but I performed a linear search over the range. Lisp makes it kind of easy with its
loopfacility:Also my only day so far with both parts under 1000.
4
u/jonathan_paulson Dec 07 '21
Python. 4/21 :) Video of me solving.
Cool problem that touches on some interesting math, some of which I explain in my video. In part 1, the optimal target is the median position. Does part 2 have a simple closed form? And 1+2+3+...+n = n*(n+1)/2 is useful to know!
I already knew median was optimal for part 1, but I wonder if it still would've been faster to just code up the brute force which extended better to part 2. Feels like there's a lesson there about how simple solutions generalize better than complicated ones :)
4
u/sim642 Dec 07 '21
My Scala solution.
In part 1, I did the naive thing, trying all positions between minimum and maximum. In part 2, I just applied the 1+2+…+n summing formula to it.
Reminds me of mean absolute error and mean square error from machine learning.
4
u/PeaceMaintainer Dec 07 '21
JavaScript:
1st Challenge
2nd Challenge
Enjoyed this one quite a bit! Wasn't expecting to get the answer so quick
4
u/Imaginary_Age_4072 Dec 07 '21
Common Lisp
Tried to get an average to start with, which didn't seem to work, so changed it to a scan through the range from min to max. Managed to remember triangular number formula though so got sub-1000 on Part 2.
4
u/programmargorp Dec 07 '21
Gradient descent is a very good way to solve this problem in log time. Matlab example attached: Note that you might get decimal points, so you might need to tweak the value returned by fminsearch a bit.
Part 1:
Part 2:
Followed by
4
u/EnisBerk Dec 07 '21 edited Dec 07 '21
Python 3
The answer for the first part is location of the median.
And for the second one, cost calculation is Gauss sum ((n*(n+1))/2) per pair.
https://github.com/EnisBerk/adventofcode/blob/master/day7/tools.py
4
u/ignurant Dec 07 '21
Ruby:
Pt 1: I'm not sure if this was just luck, but median felt intuitively like "something". It worked for the sample dataset, and (somewhat surprisingly) worked for the official set. I also perhaps got lucky with this chumpy version of median, where I'm not averaging the middle two if the input set was even.
Pt 2:
Median no longer feels intuitive, but I figured there's gotta be a mathy pattern. I suppose I'll try avg. Surprisingly, the avg of the sample dataset came to 4.9, which was suspiciously near 5, which the example says is the right target number.
.round ended up giving the right answer in the sample dataset, but not the larger set. Assuming the idea of using the average is helpful in some way (it seems like it could be?) I figured the right answer was somewhere around there.
To get the answer I printed the results for the target position range of -10..+10 just as a sanity check and was delighted to find the low fuel point was actually burried in there, right at the equivalent of Math.floor...
I'm not sure if this was just luck or not, but here's my "followed through" version:
4
u/Lispwizard Dec 07 '21
As usual, done in mostly common lisp compatible emacs lisp (elisp) on emacs 27.2 in termux on android (while in bed and under the covers).
4
u/zeekar Dec 07 '21
Another Raku solution:
4
u/gwangjinkim Dec 07 '21 edited Dec 07 '21
R
4
u/s3aker Dec 07 '21
Raku solution
4
u/Cpt__Cookie Dec 07 '21 edited Dec 07 '21
Python
A bit more mathematical solution
git
4
u/domm_plix Dec 07 '21
Perl
For the first part I had a mathy gut feeling that the solution has to be related with the
medianof the values, so I hacked up a solution (using CPAN moduleStatistics::Basicfor the statistics stuff), which worked for the test data. Tried the proper input and got a star!https://github.com/domm/advent_of_code/blob/main/2021/07_1.pl
So I assumed that part 2 will need
mean. Tried it on the test-data, didn't work because themeanwas a float, which I truncated to int. So I tried rounding it up, now it worked with test, but not with live data. Instead of thinking a tiny bit more, I thought that a brute force approach will also work and just calculated the fuel for all possible positions, which worked fast enough:https://github.com/domm/advent_of_code/commit/e687a0a93e97f4bc22c425b71162787bff03fe01
While brushing teeth (it's morning here..) I realized that I should also have tried the rounded down
mean, so I did that, and got the proper result (much faster..). Then I also used Gauss' sum formula for the fuel consumption), for this much nicer solution (which could still be enhanced, eg finding the lower of two values):https://github.com/domm/advent_of_code/blob/main/2021/07_2.pl
My favorite task this year so far :-)
4
u/OrangeredStilton Dec 07 '21
Python3 again. I freely admit to cheating today, since I thought the mean would work for part 1, and it didn't...
And for part 2, I stole Gauss' formula for a series sum:
4
u/raxomukus Dec 07 '21
Python https://github.com/fridokus/advent-of-code/blob/master/2021/7.py
Took a shortcut on the second part and used the mean to find the right spot.
For me I needed to floor the mean. I wonder if all solutions are within distance 1 of the mean? Otherwise my solution is cra(b)p
Need to search some points around the mean I think. But triangle is close enough to square that this will always work well enough
4
u/jitwit Dec 07 '21
J Programming Language
4
u/_Heziode Dec 07 '21
Ada
This is an Ada 2012 solution:
4
u/janiczek Dec 07 '21
APL
4
u/__Abigail__ Dec 07 '21
Perl
After reading the challenge, I thought we might need a variation on binary search, but after checking the input, the values were low enough to just try all positions.
Two helper methods:
Reading input:
And then:
min,maxandsumare imported fromList::Util.Full program on GitHub.
4
u/u_tamtam Dec 07 '21
Another Scala 3 solution,
it's a bit uninspiring but does the job :)
4
u/trollerskates1 Dec 07 '21
Scala using
foldLeft. Seems to be my go-to lately!4
u/beansparrow132 Dec 07 '21 edited Dec 07 '21
Python 3.8
*EDIT*
I believe there is additional requirements needed to determine whether or not to use a Ceiling or Floor when calculating the mean. Not sure how to approach determining that yet, but depending on the input it could be one or the other.
4
u/Sanduhr32 Dec 07 '21
Kotlin, O(n2) solution
4
u/death Dec 07 '21 edited Dec 07 '21
Day 7 solution in Common Lisp.
So lazy.
EDIT: I see many part 2 solutions considering positions near the mean; perhaps it makes sense. I arrived at the conclusion that the weighted median should work, though I did not implement it. Thinking about it some more, the problem is that the weights depend on the choice, so it wouldn't help. Oh well.
4
u/ACProctor Dec 07 '21
I'll be honest, I forgot about Gauss. But for anyone else thinking that today is just a one-trick solution, here's how I optimized using recursion with memoization.
Ruby:
4
u/HaiUit Dec 07 '21
Scala:
https://github.com/Fubuchi/advent-of-code/blob/master/2021/Day7/Day7.scala
Scala doesn't have partial application by default like F# so I need to mess around to make the operator look fun :D
4
u/LowAdministration462 Dec 07 '21
R
4
u/TiagoPaolini Dec 07 '21
Python
There is probably a more elegant way than just trying all the possible combinations, but the search space is small enough to allow it. I assumed that the result needed to be between the minimum and maximum initial positions, and that turned out to be correct.
Part 1 is very straightforward, just sum the absolute differences for all values. Part 2 is a bit more elaborated, it involved an arithmetic progression, but I still consider it to be easy. The fuel spent to move by n is the sum of all integers from 1 to n:
(1+n)*(n/2)(half of the sum of the extremes multiplied by the number of elements). Then sum the results for each crab, and minimize the result for all possible distances.4
u/nesvarbu Dec 07 '21
Simple Golang solution:
https://github.com/Marijus/advent-of-code/blob/master/day7/day7.go
4
u/obluff Dec 07 '21
oneliners using gnu datamash!
4
u/[deleted] Dec 07 '21
Python3
4
u/cramur Dec 07 '21
Python monte carlo-like solution. Github
Well, I was too lazy to figure out how to minimize this so I went with an old-proven way I learned when doing molecular dynamics: "If you need to minimize something, try monte-carlo"
I actually got lucky on the first try to get correct answer, as 1000 step is not enough to get it consistently. 10k is good enough for all cases in this task
4
u/P0t4t0W4rri0r Dec 07 '21 edited Dec 07 '21
Haskell:
I used the properties of the median for part1, and stole the idea of using the mean to get into the range of the solution, then i simply check the ceiling and floor and take wichever is minimal.
4
u/kuqumi Dec 13 '21 edited Dec 13 '21
JavaScript (golfed)
Tweet-sized, to be run in the input page browser console.
It should output
[part1, part2]7
u/Weird_Scallion_8727 Dec 07 '21 edited Dec 07 '21
My APL solution!
part1← {+/|⍵-⍵[⍋⍵]⊃⍨2÷⍨≢⍵}
part2←{+/∊⍳¨|((⌊+/÷≢)-⊢)⍵}
EDIT: a bit clearer, less point-free part2:
part2v2←{+/∊⍳¨|⍵-(⌊+/÷≢)⍵}
1
u/stvincent_ Dec 07 '21
For Part 1, the answer to the big puzzle is sum of distances to the median. That seems like a poor test case then because that formula is by no means the solution
1
u/mr_clemFandango Dec 09 '21
Part 2 answer in Python - not super efficient, but working!
1
u/asgardian28 Dec 07 '21 edited Dec 08 '21
Python 3 Part 1 can also be solved by taking the median
1
u/AP2008 Dec 07 '21
Rust (2ms) paste
1
u/zxywx Dec 07 '21 edited Dec 07 '21
Ruby
Part 2 takes about 0.18s.
1
u/Archer_Winter Dec 07 '21 edited Dec 10 '21
Ruby Solution
`def parse_fileFile.open('input.txt').readlines.map(&:chomp)[0].split(',').map(&:to_i)endnumbers = parse_filemax = numbers.maxp maxsums = []for i in 0..max
# part
sums[i] = numbers.map { |num| (num - i).abs }.sum
# part 2sums[i] = numbers.map { |num| (0..(num - i).abs).sum }.sump iendp sums.min`
1
u/aexl Dec 07 '21 edited Dec 07 '21
Julia
Simple brute force (and knowing what a triangular number is).
Github: https://github.com/goggle/AdventOfCode2021.jl/blob/master/src/day07.jl
1
u/AKSrandom Dec 07 '21 edited Dec 07 '21
Part 1 : https://math.stackexchange.com/q/113270
For Part 2 , applying similar , logic one gets the mean will minimize the required sum (maybe?), and hence after trying with the mean rounded up and down, I got it
1
u/st_ranger123 Dec 07 '21 edited Dec 07 '21
Day7 Problem 2 Javascript Solution
For Problem1 replace
by
1
u/ollien Dec 07 '21 edited Dec 08 '21
Rust
I did it a bit of a naive way and it worked out better than it had any right to, haha
1
u/Opposite-Cry-6703 Dec 07 '21 edited Dec 07 '21
Python 3
Part 1
Part 2
1
u/Sallith Dec 07 '21 edited Dec 07 '21
Javascript
I iterate through all the possible final position. I memoized the sums of x and its previous numbers in an array so I didn't have to compute the same result multiple times and then by reading the comments I totally forgot it could be trivially computed with x * (x + 1) / 2.
1
u/SadBunnyNL Dec 07 '21 edited Dec 07 '21
Java: (and I didn't know about Gauss' range sum formula)
1
u/jdnewmil Dec 07 '21 edited Dec 07 '21
R
Mean and median would be theoretical optimum values if no rounding were occurring so you have to clean up with a search for a general solution (found this out the hard way since the example worked but the data did not).
1
u/theabbiee Dec 07 '21
Both Parts In Python
1
u/psiphiorg Dec 07 '21 edited Dec 08 '21
Spreadsheet solution (Excel, Google Sheets):
=ABS(B$2-$A3)=SUM(B3:B1002)=MAX(B1004:BXL1004)(solution for part 1)=ABS(B$2-$A3)*(ABS(B$2-$A3)+1)/23
u/dtinth Dec 07 '21
The number 1000 was arbitrarily chosen, it was a total fluke that it worked 😅
3
u/hugh_tc Dec 07 '21 edited Dec 07 '21
Python 3, 76/30.
Part 1, Part 2, and (edit) the cleaned-up version.
It's helpful to know that the nth triangular number is (n*(n + 1) / 2). Saves some keystrokes! I notice that the crabs are headed towards a "massive underground cave system" -- maze tomorrow?!
3
u/mwk0408 Dec 07 '21 edited Dec 07 '21
79/26, python3
solution
forget to include the maximum number, fortunately the answer is still correct
3
u/2SmoothForYou Dec 07 '21 edited Dec 07 '21
Haskell
paste
Really simple today, nothing too fancy
Edit: Cleaned up version with median/mean improvements and improvement I found in u/brandonchinn178 's code
paste
3
u/[deleted] Dec 07 '21
Rust
Another one line change between parts 1 and 2 using just an arithmetic sum formula!
Part 2
3
u/baer89 Dec 07 '21 edited Dec 07 '21
Python
Easy one but not easy enough for points.
Part 1:
Part 2:
3
u/BluFoot Dec 07 '21
Ruby 79 bytes
3
u/giftpflanze Dec 07 '21
Factor
This day felt a little too easy.
3
u/MichalMarsalek Dec 07 '21 edited Dec 07 '21
Nim
part 1 = median, part 2 = mean
using my templates.
3
u/abnew123 Dec 07 '21
Java: https://github.com/abnew123/aoc2021/blob/master/aoc2021/Day7.java
Terribly ugly solution, but its the first thing that came to mind. Stream abuse to keep everything in two lines.
3
u/marshalofthemark Dec 07 '21 edited Dec 07 '21
Ruby (only runs in 3.0+)
Easiest problem since day 2 IMO. Maybe even easier.
3
u/ritobanrc Dec 07 '21
Rust, basic bruteforce solution. Played around with trying to find an analytic solution for a couple mins, but ended up just brute forcing it, and surprisingly, its not absurdly slow.
3
u/Sourish17 Dec 07 '21
Python 3
A refreshing start to the week so far ;)
Solution + mini-write up:
sourishsharma.com
3
u/wasi0013 Dec 07 '21
Elixir
3
u/landimatte Dec 07 '21 edited Dec 07 '21
Common Lisp
Brute-forced it:
Note: for part 2, I did not even bother using the proper formula; I simply simulated it, and only had to wait for 20 seconds:
3
u/French__Canadian Dec 07 '21 edited Dec 07 '21
My 3 lines solution in Q. It is very... horizontal. I could easily have written a function to calculate the distance instead of inlining it twice, but 124 character lines ain't THAT bad...
alright, creating a distance function makes it 82 characters wide instead
edit #2: looking at somebody else's Q solution, i realized i was being a big idiot and was finding the min, then where that min was, then recalculating the min again
This is a non-stupid version of both parts
3
u/dogsrock Dec 07 '21
Woo hoo! Solving a puzzle in the first 30 mins for me! :)
Here's how I did it (Python 3.6)
3
u/BradleySigma Dec 07 '21
matlab
3
u/Spelljack- Dec 07 '21 edited Dec 07 '21
Python:
Part 1:
Part 2:
adding gauss formula to the comprehension was a bit too much.
3
u/martino_vik Dec 07 '21
Today was my personal best day, needed about half an hour for both in Python 3.10: [Part 1](https://topaz.github.io/paste/#XQAAAQDFAAAAAAAAAAAxnIhFo9JuI0mU+VldtRuCXPE8sgV8B3TJaU5rja3kQLzOOpJY2x4HA+tyGpgHpkpnrX+v9UPXLPTUG/tG80HznmqZh2n5nGMiWph6bGUhjqSy4rjCiaZhLoBXo+RadDu0oFKaNc85dageev78npBiu1FoqFycrgwXS337oxPsQ2RKpEnW3//ucKAA), [Part 2](https://topaz.github.io/paste/#XQAAAQDZAAAAAAAAAAAxnIhFo9JuI0mU+VldtRuCXPE8sgV8B3TJaU5rja3kQLzOOpJY2x4HA+tyGpgHpkpnrX+v9UPXLPTUG/tG80HznmqZh2n5nGMiWph6bGUhjqSpSBZ4Ds++EmQNI/LyDqeKJhoWoQeoS+e4G5OgY9D1nh0XSSLdslhU6IKY4xH+SzlNwNLesBIvYuUzdArKxpr48B//xzibIA==)
3
u/ri7chy Dec 07 '21
PythonCode
runs in about 0.8s with sum-formular.
good day.
any suggestions to speed this up?
3
u/Perska_ Dec 07 '21
C# https://github.com/Perska/AoC2021/blob/master/AoC2021/Days/Day07.cs
I was worried that my approach would take too long for Part 2, but apparently it wasn't. Maybe me memorizing the fuel costs helped?
3
u/jfb1337 Dec 07 '21
Python:
3
u/xe3to Dec 07 '21
part 2, python:
this was WAY easier than any of the other ones. just had to use gauss' famous formula. failing that
sum(range(p-k)+1)would've worked as well, but taken longer.3
u/nibbl Dec 07 '21 edited Dec 07 '21
Rust (beginner)
Not a great way of doing it.
Had a weird experience today. My part 2 result for the test input was consistently off by two no matter how many different ways I calculated the answer. Eventually in frustration I just ran it with the real input and threw the number in and it was accepted. Cannot for the life of me figure out what was happening.
3
u/ICantBeSirius Dec 07 '21 edited Dec 07 '21
Swift - update
This version uses median to find the part 1 optimal position and mean for part 2Edit: Edited to take into account u/asdf-user 's comment
3
u/Extension_Wheel_2032 Dec 07 '21
Clojure. Not fast at all for large input (~5 sec) but it works!
3
u/sortaquasipseudo Dec 07 '21
Rust
I'll be live-streaming my solutions at twitch.tv/jeffanddom. Please stop by and help me out in the chat! Video archive is here.
3
u/ka-splam Dec 07 '21 edited Dec 07 '21
Prolog (SWI)
Fast enough to run on https://swish.swi-prolog.org/ , create a new empty program, paste the code on the left, put
solve.in the box on the lower right, click run. It should solve the examples, can paste your numbers directly over the Crabs list as long as you keep it on one line. Takes ~6 seconds for my Part 1 input.Part 1:
43,092,516 inferences, it tells me.
Part 2 I went a bit wrong and tried to write it like a Factorial function, and it was taking ages. I puzzled over it for an hour wondering how I could add more constraints or tabling/memoizing the calculation, before realising the new fuel cost is a direct calculation with Gauss's formula - he famously observed that if you reverse a list and add to the original:
All the columns sum to the same number, and that number is 1+ the max value. So this list adds 6, five times. And since you add each number twice, (6*5)/2 is the sum.
Part 2, breaks out the fuel cost into a separate predicate as it's getting a bit dense:
66,554,471 inferences and ~9 seconds, it tells me.
3
u/Chebtis Dec 07 '21
Powershell
Part 1: https://raw.githubusercontent.com/kloo/aoc2021/main/07/7a_2021.ps1
Part 2: https://raw.githubusercontent.com/kloo/aoc2021/main/07/7b_2021.ps1
Didn't remember there's a formula for triangle numbers when I was looking for a quick way to get them (or that they're called triangle numbers) so I just built a lookup array. Seems to run in around 7 seconds hot or cold.
3
u/[deleted] Dec 07 '21
Python
3
u/complyue Dec 07 '21
Haskell
3
u/egel-lang Dec 07 '21 edited Dec 07 '21
Egel
On github
task 1 example
3
u/LionSuneater Dec 07 '21 edited Dec 07 '21
Python
Every time I use
rangeornp.arangeI always put the stop parameter one short. Every, merry time. It's been years now.edit: The
costfunction here is silly and very slow. The sum from 1 to s is just s*(s+1)/2, socost = lambda s: s*(s+1)/2is preferred.3
u/alchzh Dec 07 '21 edited Dec 07 '21
Python
quick and simple comprehension
Part 1
int(min(sum(abs(i - k) for k in pos) for i in range(1, max(pos)+1)))Part 2
int(min(sum(abs(i - k)*(abs(i - k)+1)/2 for k in pos) for i in range(1, max(pos)+1)))EDIT: why even float
Part 1
min(sum(abs(i - k) for k in pos) for i in range(1, max(pos)+1))Part 2
min(sum((abs(i - k)*(abs(i - k)+1))//2 for k in pos) for i in range(1, max(pos)+1))3
u/hendykombat Dec 07 '21
Kotlin
Noticed the median worked in part 1 and the mean for part 2.Had to floor and ceil the mean though, since it could be either depending on the data input. (floor for the main input, ceil for the test).
PS: I find crab math to be more realistic
3
u/autid Dec 07 '21
FORTRAN
Actually just looped through and saved minimum fuel for initial solve but it felt unsatisfying so I did a binary search.
3
u/isukali Dec 07 '21 edited Dec 07 '21
C++ Solution:
Part 1 (median):
Part 2 (mean):
3
u/xoronth Dec 07 '21
GNU Smalltalk:
3
u/rukke Dec 07 '21 edited Dec 07 '21
JavaScript
I don't know if I was just unlucky with my input today: for part2 ceiling the avg gives the correct answer for the test data, but not the real input which needs flooring. Spent some time scratching my head over this until I caved and returned the min of the both. (EDIT, better naming)
3
u/r1ppch3n Dec 07 '21
Rust
3
u/Edicara237 Dec 07 '21
A gradient search solution in Clojure:
paste
It assumes that there always is a fuel difference between two adjacent positions and that there is only a single optimal position.
3
u/mariushm Dec 07 '21
Here's my PHP solution : https://github.com/mariush-github/adventofcode2021/blob/main/07.php
Probably not the "least cpu cycles" solution, but it's short simple to read code.
3
u/0rac1e Dec 07 '21 edited Dec 10 '21
J Language
Translation of my Raku solution. Like that solution, I'm pulling in
medianandmeanfrom the stats lib.I just searched the J wiki for "abs" and found the
(>-<)&0snippet, which returns-1,0, or1... so I just combined it with*, which works as an abs function, but I wonder if that's the "approved" way. I'm looking forward to reviewing other J solutions.Notes
I replaced my crappy
absfunction with magnitude (|). Thanks u/u794575248.I realised my solution was not valid for both the sample input, and the test input. If I use ceiling (<
.) it's now correct for the full input, and if i use floor (>.), it's correct for the sample.It seems the approach is to try both the floor and the ceiling, and take the min, as in my revised solution to Part 2.
3
u/staletic Dec 07 '21 edited Dec 07 '21
Again, a compile time C++ solution: https://godbolt.org/z/fzG17KfqT
Admittedly, it looks crowded. Positions, cost calculations and the call to
ranges::minshould have been 3 separate things:constexpr auto pos = views::iota(minmax.min, minmax.max + 1);constexpr auto costs = pos | views::transform(...);constexpr auto cheapest = ranges::min(costs);A more readable version: