r/adventofcode • u/daggerdragon • Dec 06 '21
SOLUTION MEGATHREAD -π- 2021 Day 6 Solutions -π-
NEW AND NOTEWORTHY
We've been noticing an uptick in frustration around problems with new.reddit's fancypants editor: mangling text that is pasted into the editor, missing switch to Markdown editor, URLs breaking due to invisible escape characters, stuff like that. Many of the recent posts in /r/bugs are complaining about these issues as well.
If you are using new.reddit's fancypants editor, beware!
- Pasting any text into the editor may very well end up mangled
- You may randomly no longer have a "switch to Markdown" button on top-level posts
- If you paste a URL directly into the editor, your link may display fine on new.reddit but may display invisibly-escaped characters on old.reddit and thus will break the link
Until Reddit fixes these issues, if the fancypants editor is driving you batty, try using the Markdown editor in old.reddit instead.
Advent of Code 2021: Adventure Time!
- ACHIEVEMENT UNLOCKED: Adventure Time!
- SUBMIT YER ADVENTURES, MATEYS!
- Full details and rules are in the submissions megathread: π AoC 2021 π [Adventure Time!]
--- Day 6: Lanternfish ---
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.
54
u/JohnnyWobble Dec 06 '21 edited Dec 06 '21
665/97 [Python]
First time ever getting on gobal leaderboard!!
36
u/I_LOVE_PURPLE_PUPPY Dec 06 '21 edited Dec 06 '21
MATLAB:
O(log(n)) time complexity for n steps with matrix power by repeated squaring (or even faster, albeit less precise, with diagonalization methods)!
24
u/CCC_037 Dec 06 '21
Rockstar
Part 1 (faster version)
Part 2 (very similar, only the counter changed)
7
u/smrq Dec 06 '21 edited Dec 06 '21
JS, 79/2651
I made this one too hard. My extremely naive part 1 didn't cut it for part 2, but I went overboard when I saw the power of 2 number of steps.
That said, my solution (slightly modified) was able to calculate in 138ms that in 217 steps, there will be [very long number omitted] fish, given my input. I don't know how to check that...
(Edit: just for fun, I got a result for 222 in 46.7 seconds. It's a bit over 150,000 digits long.)
7
u/askalski Dec 06 '21
C++, now with more more magic numbers!
https://gist.github.com/Voltara/b1164bf6efa817908c763fda42b3cea6
7
u/activeXray Dec 07 '21 edited Dec 07 '21
Julia
6
u/[deleted] Dec 06 '21
Here is my newbie solution in Python.
6
u/OverjoyedBanana Dec 06 '21 edited Dec 07 '21
Python 3 (dynamic programming)
Just write the rules of the game and leave the optimization to the cache...
edit: code formatting
5
u/Solarmew Dec 06 '21 edited Dec 07 '21
Python 3
5
u/armeniwn Dec 06 '21 edited Dec 07 '21
I guess this is what happened to most people:
First approach: let's calculate this day by day. Oh my god, my computer ran out of memory no matter what language I use!
Second approach: I should pre-calculate starting from small number of days. I should store and reuse my calculations as I go up. Oh my god, I 've got an answer in seconds, no matter what language I use!
Third approach: I will try to do better. OK, I can see that the heart of the problem is solving `A(n) = 2*A(n-1) + 1`. I can prove that `A(n) = 2^n - 1` which is probably the best solution I can come up with.
This was my second approach:
5
u/yorhodes4 Dec 07 '21 edited Dec 07 '21
rust
https://github.com/yorhodes/advent-of-code/blob/master/2021/day6/src/main.rs
love when this happens
4
u/polettix Dec 06 '21 edited Dec 06 '21
Raku solution
Edit: take inputs directly from file.
Edit: moved to paste.
4
u/xenopunk Dec 06 '21 edited Dec 06 '21
I love this problem because ultimately it sounds really difficult but only if you don't spot the trick. If you are thinking efficiently it's literally "Count how many times n appears in this string". Loving all of the computation time issues, some people going to be hitting themselves.
Now I have been doing all the problems in Excel and this was a really nice one for Excel to solve ngl. Formula wise it more or less matches what other people have done with states in steps 8->7, 7->6 ..., instead being C3 <- B2, etc.
4
u/corynezin Dec 07 '21
Using Python and theory of LTI systems.
4
u/FrancRefect Dec 07 '21 edited Dec 08 '21
My Rust solution, using a 'circular buffer'. Based on the fact that no fishes will ever have a lifetime over 8. Using modular arithmetic, moving array elements can be avoided.
Fishes with a lifetime of
0will have a timer of8on the next iteration (newborns). Fishes on the current generation with a timer of7today will have a timer of6on the next day. So, the number of fishes that are resetted today (timer of0) must be added to the one with a timer of7.Edit: Additionnal explanation in the paste
paste
3
u/BestWifu Dec 06 '21 edited Dec 06 '21
Javascript (2417/1736)
Had some problems with the fish array being too big, but then I realized that I didn't need to keep track of each individual fish.
Part 1
Part 2
3
u/Chrinkus Dec 06 '21 edited Dec 06 '21
My C Solution
I knew one of these was coming! Of course in the past I was able to just brute-force the problem and tab-out while it completed. Kudos to /u/topaz for creating a problem that made me consider playing with my
limits.conffile.Couldn't get part 2 last night. Best solution was to just go to bed and sleep on it.
In the end, this function replaced 50+ lines of brute-y code:
3
u/activeXray Dec 07 '21 edited Dec 07 '21
Clojure
3
u/ravi-delia Dec 07 '21 edited Dec 08 '21
Feels good when you happen to get the efficient solution first thing.
Common Lisp
3
u/pistacchio Dec 07 '21 edited Dec 08 '21
Typescript:
3
u/arthurmluz_ Dec 07 '21 edited Dec 08 '21
My python solution:
I've transformed the list into a dictionary, so it doesn't have to make a giant list.
2
u/strobetal Dec 06 '21 edited Dec 06 '21
python (1531 / 310)
load_csv is a util function:
2
u/wimglenn Dec 06 '21 edited Dec 06 '21
Python
2
u/MToTheAdeline Dec 06 '21 edited Dec 06 '21
That moment when u see part 2 is just changing ur loop variable,,,,,, and then your code never completes π
Rust, I'm a beginner at it tho πΆ
2
u/areading314 Dec 06 '21
Clojure
2
u/Veregon74 Dec 06 '21 edited Dec 07 '21
C#
I didn't do the copying, instead used mod to figure out which bucket to spawn and a queue to hold juveniles.
2
u/LongInTheTooth Dec 06 '21 edited Dec 07 '21
Clojure with a vector instead of a map:
2
u/[deleted] Dec 06 '21 edited Dec 07 '21
I know it is bad etiquette to include one's problem instance in code instead of reading from standard input, but I don't have much time today! Also, I don't know how to paste code here on reddit and it becomes a mess
2
u/blafunke Dec 07 '21 edited Dec 07 '21
Haskell
2
u/Ryles1 Dec 07 '21 edited Dec 07 '21
Python 3 Like lots of people, I had to refactor after my brute force solution wouldn't work for part 2. Finished just in time for day 7. Here it is:
https://github.com/Ryles1/AdventofCode/blob/main/2021/day6.py
2
u/gala0sup Dec 07 '21
My solution, I think this is pretty fast
2
u/mr_clemFandango Dec 09 '21
bodgy python solution:
2
u/fish-n-chips-uk Dec 12 '21 edited Dec 13 '21
Basic (QBasic 4.5)
(Part 1 only; part 2 causes overflow. Hardcoded sample input)
40
u/4HbQ Dec 06 '21 edited Dec 06 '21
Python, using a 9-element list of ints to keep track of the counts:
25
u/jonathan_paulson Dec 06 '21
Python. 2/16 :) Video of me solving.
Cool part 2; I hope we see more problems where the code running fast is a concern.
20
u/ignurant Dec 06 '21
I first solved with a typical "simulate each fish" like a lot of other folks I'm reading about. Overcoming the exponential growth issue was exhilarating. I was demoralized for a few minutes, assuming there was some hidden super easy math trick that can spit the answer out with a simple function. After a minute of stepping away, I realized that I just need the number of fishes in each stage and can promote the whole crew each tick. It was a rollercoaster, and I felt awesome thinking about all of the wasted compute power and ram being used to essentially perform the same lifecycle on all those individual fish.
It looks like there's a few other Ruby submissions that look a lot like mine, but using arrays instead of hashes. I was going to use arrays, but it was easier for me to grok a fish resetting it's cycle with a hash. I figured I'd submit mine because of that difference.
Ruby
15
u/4HbQ Dec 06 '21 edited Dec 06 '21
Python, using recursion on the age of the fish:
You might have seen some posts with numbers like 1421 or 6703087164. These arise because of the following relation: each fish with d days left "creates" two new fish, one with d-9 days left (the future version of this fish) and one with d-7 days left (the fish it created).
Since f(80) = 1421, this means that a fish with 80 days left will "create" 1421 new fish. This way, we can compute all other numbers as well, e.g. f(256) = 6703087164. So if you start with 2 fish with 77 days left (t=3) and 1 fish with 76 days left (t=4), you end up with 2 Γ f(77) + 1 Γ f(76) = 2 Γ 1154 + 1034 = 3342 fish.
14
u/relativistic-turtle Dec 06 '21
IntCode
(...or should I say Int64Code? XD)
Note: assumes 300 initial lanternfish in the input, and that the IntCode-VM is 64bit (32bit IntCode-architectures are sooo yesterday!)
Luckily I had anticipated the need for large (64-bit at least) when coding my VM. Still had to repair my division-routine which did not yet have support. (The IntCode-instruction doesn't have division. Had to implement a long division algorithm for that). Once that was fixed my part 1 solution immediately generalized to part 2.
13
u/Baby_Gary Dec 06 '21
Python 3
I noticed that the amount of fish at each age state at a particular time step can be expressed as a vector, and I could multiply that vector by the 9x9 matrix M to go forward one time step.
From there, the solution was easy to calculate.
Where M is the matrix above, 256 is the amount of time steps, and initState is the list given as the puzzle input.
Edit: formatting
11
u/Mathgeek007 Dec 06 '21 edited Dec 06 '21
Excel - 681/149, 5:10/6:34
Pretty easy - I counted the number of each fish, put them in rows 1-9, then each row looked at the previous row for counts, except for 8, which looked at 0, and 6, which looked at 7 and 0. Really low delta! Very proud of myself for this one, redemption after the last few days!
VIDEO OF SOLVE
11
u/encse Dec 06 '21
C#
https://github.com/encse/adventofcode/blob/master/2021/Day06/Solution.cs
10
u/Tails8521 Dec 06 '21 edited Dec 06 '21
Motorola 68000 assembly (On a Sega MegaDrive)
The lack of native 64bit support on that CPU makes it messier than what it was before I added part 2 (I originally used 32bit counters, but, yeah, these are nowhere near enough for part 2, they would just overflow a bunch of time), still, runtime remains pretty fast, less than 20ms, not bad for such old hardware.
10
u/[deleted] Dec 06 '21 edited Dec 06 '21
I think my Python solution is quite concise and efficient. I realised that you only have to actually mutate one index for each iteration.
9
u/voidhawk42 Dec 06 '21 edited Dec 06 '21
APL:
9
u/ephemient Dec 06 '21 edited Apr 24 '24
This space intentionally left blank.
8
u/rabuf Dec 06 '21
Common Lisp
Straightforward. I did it the dumb way first (created a list of all the fish and simulated them) but it was apparent that wouldn't work for part 2, just wanted to code up my fastest thought for part 1.
I replaced that with:
Wordy, but
psetflets me set all of them at once, no temporary variables or tables.8
u/gasperixx Dec 06 '21
Google Sheets
This was a real relief after yesterday's troubles with resources... 10 min.
8
u/autid Dec 06 '21
FORTRAN
Pretty happy with this one.
8
u/artemisdev21 Dec 06 '21
Part 2 in a Python one liner. Probably not the most efficient, but still under a second.
Replace
256with80for part 1, ofc.Abuses mutable defaults to achieve memoization, in a recursive lambda that's defined in an assignment expression...
Also, a Web Assembly solution.
8
u/Smylers Dec 06 '21 edited Dec 06 '21
Vim keystrokes, animated. I recommend only running this on the sample input, but it is fun to watch:
I'll try to put a video up later.Video now availableIn Ubuntu Mate (and possibly elsewhere) you can type π with
β¨Ctrl+Shift+Eβ©fishβ¨Spaceβ©β¨Enterβ©and π withβ¨Ctrl+Shift+Eβ©fishβ¨Spaceβ©β¨Spaceβ©β¨Enterβ©.8
u/__Abigail__ Dec 06 '21 edited Dec 06 '21
Perl
A second, but different solution. This one is based on matrix multiplication. If we have the number of fish generation
nin a vector, with each element on indexithe number of fish with its timeri, thenf_n+1 = A * f_n, whereThen we have
f_n+1 = A * f_n. Or, in general,f_g = A^g * f_0.We then first read in the data, and create the base vector:
Next, a matrix to do the multiplication:
Now, calculating the results is easy:
This runs in time
O (t^2 * log g), wheretis the maximum value of a timer, andgthe number of generations.Full program
8
u/ywgdana Dec 06 '21
C# repo
Implemented a dumb, naive actually-append-fish-to-a-list solution for Part 1 knowing full well this was going to be a "Part 2 will laugh at your brute force method" day. Was not disappointed.
I scratched my head for a while thinking of approaches until I saw a hint that you only need to track the number of fish in each day of the reproductive cycle and then the array-shifting solution became immediately obvious.
I was surprised to learn there's no Sum() extension method for collections of type ulong in C# :O
8
u/joshbduncan Dec 09 '21
Python 3: Used a non-optimized approach for part 1 knowing all too well that it wasn't going to work for part 2. Took some time to work out the math but here's the optimized version.
15
u/motek96 Dec 06 '21
Emojicode
7
u/oantolin Dec 06 '21
I couldn't tell you why I decided to use Common Lisp's
rotatefto implement the function that computes the future number of fish. I guess maybe I thought 9 variables aren't that many? At any rate the function is pretty short:Here's the full program.
7
u/TheShallowOne Dec 06 '21
In comparison to most solutions using shifted arrays, i used maths (and Python).
I determined the formula for the amount of children each generation creates, and then summed these up.
Python Solution and Jupyter notebook with details.
6
u/constbr Dec 06 '21 edited Dec 10 '21
Javascript 634/867
I brute-forced part 1, but part 2 was crashing with out-of-memory errors. Took a while to realise you don't really need specific fishes, only how many of them in each generation.
Part 1
Part 2
6
u/u794575248 Dec 06 '21 edited Dec 06 '21
J Language (an array programming language based primarily on APL)
6
u/Mamu7490 Dec 06 '21 edited Dec 06 '21
I quite like my solution, i think its pretty elegant. I made a challenge to myself to only use pure python for this year, and this one worked out quite well.
6
u/yschaeff Dec 06 '21 edited Dec 06 '21
Python w/o numpy
6
u/mockle2 Dec 06 '21 edited Dec 06 '21
python
6
u/Synedh Dec 06 '21 edited Dec 06 '21
Python
KISS, no import, no dict.
Idea here is just to count fishes per days remaining before they duplicate. Each day we take the first element, switch all others from one day (witch is the same thing as popping first element) then add them back to the sixth day cell, and add the same amount of newborns.
You can use slicing too to rotate the list :
EDIT later, because I finally understood why it is possible to do it by just inserting in the good cell. Fishes don't need to move in the list when index do the work. We just have to inject the good amount on the good day. First day index 0 goes in index 7, second index 1 in 8, 2 in 0, etc.
6
u/conkerandco Dec 06 '21 edited Dec 06 '21
Python
β
6
u/janiczek Dec 06 '21
APL, part 1 (yes it runs out of memory on part 2)
6
u/sappapp Dec 06 '21
Python
6
u/_mattmc3_ Dec 06 '21
Fish shell solution
A fitting solution to the lantern fish puzzle in fish code.
6
u/Zeeterm Dec 06 '21
C# / Linqpad
A second solution, (Is using a matrix multiplication library cheating?):
So I realised that we can essentially pre-calculate the M256 transition matrix so we get an analytical / O(1) solution.
It's been bothering me all day that there wasn't an analytical solution so I'm happy I essentially found one.
6
u/vbe-elvis Dec 06 '21
Kotlin: Just for the fun of it, made my solution short and unreadable:
6
u/Smylers Dec 06 '21
Vim keystrokes efficient solution for both parts. Not as fun to watch as my earlier Vim solution, but it does run in reasonable time and space, even on the real input.
Load your input, ensure
gdefaultis off, and maybe turnnumberon to see what's happening:And that's your partΒ 1 answer.
After which you can get partΒ 2 with:
This one isn't very complicated, as these things go. See if you can work it out, and if not do ask questions below.
6
u/baer89 Dec 07 '21
Python
The lanternfish are too bright!
Part 1:
Part 2 (Spent way to long trying to math a formula for this. Had to rethink my approach):
10
u/paulcole710 Dec 06 '21 edited Dec 06 '21
Python 3
This did even 10,000 days nearly instantaneously.
datais whatever your input is.5
u/oantolin Dec 06 '21 edited Dec 06 '21
Nice easy one today, the Perl code fits here:
It feels nice to guess correctly where part 2 is going and write code you can just rerun with a bigger number. :)
5
u/EliteTK Dec 06 '21
Python 3 - The dynamic programming approach
5
u/qwesda_ Dec 06 '21
Postgresql
Part 1 GitHub explain.dalibo.com
Part 2 GitHub explain.dalibo.com
I'll try to see if I find a non-recursive version later ...
5
u/tymscar Dec 06 '21
I think today's part 2 was very difficult because it took me a long time to realise that you dont have to find a fancy formula at all, you can still `bruteforce` it, its just that you dont need to increase any array for that.
Part1 and part2 in Javascript
5
u/sefujuki Dec 06 '21 edited Dec 06 '21
dc
After replacing all commas in input with spaces.
Usage:
tr ',' ' ' <day06.txt |dc day06.dc5
u/Tipa16384 Dec 06 '21
Python
5
u/bbgmp Dec 06 '21
Python 3
Github
Foolishly set up a wonderful OOP solution for Part 1 with each fish represented by its own object able to recursively call a global fish factory in order to give birth.
Tested this solution with 256 days for the example set... after 1 hour of processing without returning a result, decided I needed a better solution.
Kept both versions as a reminder to myself that not every problem warrants an OOP solution.
5
u/kbielefe Dec 06 '21
Scala 3
One of the shorter solutions in lines of code, but one of the longer solutions in terms of development time.
5
u/wzkx Dec 06 '21
Python
Haha it's simple when you think. But you have to think!
5
u/advent_of_bsod Dec 06 '21
130 character python solution (code golf'd by my discord group into something ridiculous):
(130 characters ignoring final newline.)
5
u/Breadfish64 Dec 06 '21 edited Dec 06 '21
Matlab
Given the number of fish for the first ten days, the linear recurrence relation for the total number of fish is
f[n] = f[n-1] + f[n-7] - f[n-8] + f[n-9] - f[n-10]. I used Matlab to find the closed form solution which can be evaluated for any number of days. It works for the example but low precision caused it to be off by one for the real input.the expanded function is
5
u/tomflumery Dec 06 '21
05ab1e (use legacy, new version is too slow)
5
u/skawid Dec 07 '21
Python! A disgustingly small amount of code for how long it took me to figure out.
4
u/MuumiJumala Dec 06 '21
Ruby (77 bytes)
4
u/jaybosamiya Dec 06 '21
APL
First line reads the input into an array of characters. Second line sets the print precision to a large enough value so that we don't get the answer in scientific number notation, but instead as a full integer (the result is large enough that we need to do this). The next line sets
lto the parsed out numbers by splitting on commas, partitioning the result and evaluating each partitioned part. Next line setscto the number of fish each of the internal counter 0, 1, .... 8. Thus,cis now an array of 9 numbers. Next line setsgto be the "day update" function, which shifts everything over and adds the thing at the 0 position into the 6th and 8th positions. Finally, the last 2 lines rung80 and 256 times respectively, applying them toc, and then taking the sum over the results, to get the answers.4
u/sim642 Dec 06 '21
My Scala solution.
I already went with a map from timer to count in part 1, which made part 2 very easy.
4
u/Floozutter Dec 06 '21
Python, 939/915. I didn't score, but it felt super satisfying to arrive at this solution using recursion and memoization!
4
u/polettix Dec 06 '21
Another Raku variation, unmoving array. Might just as well be implemented in C or assembly (probably the reading part might be more challenging in this case).
4
u/zyonsis Dec 06 '21 edited Dec 06 '21
Python3, recursion with memoization. Seems like my brain likes to default to DP for these ones.
4
u/[deleted] Dec 06 '21 edited Dec 06 '21
python
O(1) after reading in. part 1 and 2. 3 lines.
This is a closed form solution where I'm just doing the lookup of the answer. It outputs a complex number where real part solves part 1 and imaginary part solves part 2 (only so I could do both solution lookups at the same time trivially). Might change that later just wanted to do it fast.
(If you want details on where the closed from let me know and I'll write it out when I awake or in a little bit)
EDIT: it seems people don't have inputs with a 6 in it? if that's the case you can remove the last item of the two lists, we'll see EDIT 2: removed
4
u/XamazingX5 Dec 06 '21
2765/5305 I think this Python3 solution is really tidy, but it took me way longer than I care to admit to figure out to use a dict.
4
u/CutOnBumInBandHere9 Dec 06 '21
Python, treating the problem as one of transitions between states. The transition matrix from one day to the next is given by a shift, with a single extra 1 for resetting the old fish to six days. The state after n days can then be found from the nth power of the transition matrix:
4
u/__Abigail__ Dec 06 '21 edited Dec 06 '21
Perl
This is just an example of a constant recursive sequence
We'll use an array
@fish, with 9 elements, where$fish [$i]is the number of fish with internal timer$i.Reading in the data is easy:
Now just create the next generation the appropriate amount of times:
Full program on GitHub.
4
u/RoccoDeveloping Dec 06 '21
Rust, very fast solution (~2 us for Part 2). I'm glad Part 2 was just as expected.
4
u/redditnoob Dec 06 '21
PostgreSQL
4
u/codesammy Dec 06 '21
Can there be a formula to calculate this instead of iterating over the days?
For the input "3,4,3,1,2" there are 10 fishes after 9 days: "1,2,1,6,0,1,2,3,3,4,8"
"1" after 5 days turns into "1, 6, 8"
"2" after 5 days turns into "0, 2"
"3" after 5 days turns into "1, 3"
"4" after 5 days turns into "2, 4"
So if we had a formula for one fish starting at "1" and know how many fish it turns into after n days, we can sum them together and get the full sum.
But I don't know how to make this formula.
And if such formula cannot exist, I don't know how to prove that.
4
u/Derp_Derps Dec 06 '21
Python
I first "simulate" how a single fish will reproduce iteratively. This will create a lookup table that contains the number of fishes for a given time point. Then I just generate the sum over every "input fish".
4
u/udvlp Dec 06 '21
C
4
u/SpaceHonk Dec 06 '21
Swift
https://github.com/gereons/AoC2021/blob/main/Sources/AdventOfCode/puzzle6.swift
keep an array of counts per age, calculate the next generation, swap arrays, repeat until done
4
u/MyCodesCompiling Dec 06 '21
Python
4
u/RandoArcher0815 Dec 06 '21
Python 3
Quite new to Python, so some of this might not be good practice.
4
u/paul2718 Dec 06 '21
C++ at compile time...
Could probably be further abbreviated...
https://godbolt.org/z/WKd4Efj7x
4
u/constxd Dec 06 '21
Ty
4
u/rawlexander Dec 06 '21 edited Dec 06 '21
R / Rstats:
Julia:
4
u/mapthegod Dec 06 '21 edited Dec 06 '21
Rust:
Keep all of the fishes grouped by their age, instead of handling individual fish.
Part 2 runs in ~ 2 us.
4
u/xkev320x Dec 06 '21
Rust, went through different stages here like most I imagine. Did the naive brute-force approach for part 1, realized it won't work for part 2 and had to rethink.
Took me a while to get the idea with just counting the different length values per day per number but then did that and then kinda saw (thanks to some hints here) that it is basically just a rotate.
4
u/[deleted] Dec 06 '21 edited Dec 06 '21
My solution in Python. Today was fun and very easy. I immediately came to the same conclusion as others here to simply track the number of fish per age group instead of modeling each fish separately.
4
u/[deleted] Dec 06 '21
My solution in Rust, took 158seconds to get me the solution to part 2 (runtime) using multithreaded programming. 3ms for getting the solution to 80 days, pretty proud (day 6 of using Rust as well). I first tried to find exponential rate, but to no avail (I came pretty close)
4
u/BeYuu Dec 06 '21
Haskell solution: Source (Github)
4
u/kyletbyrne Dec 06 '21
A very ruby'ish Ruby solution
4
u/tcbrindle Dec 06 '21 edited Dec 06 '21
C++
I enjoyed today's problem! I started off with a solution that used
std::rotate(), but then I realised that rotation wasn't really necessary and we could instead just use a "cursor" that updates mod 9.Github
4
u/EnisBerk Dec 07 '21
Python 3
Keeping newborn fish in a different array makes things easier to follow.https://github.com/EnisBerk/adventofcode/blob/master/day6/tools.py
4
u/cesargar Dec 07 '21
C
https://github.com/HashTag42/AdventOfCode/blob/main/2021/2021-06/2021-06.cs
Results:
4
u/Routine_Elk_7421 Dec 07 '21 edited Dec 07 '21
part 2 code golf in python3. First time code golfing. Any suggestions?
4
u/Spirited-Airline4702 Dec 07 '21
Python
4
u/gigajul Dec 07 '21
Python - a recursive approach.
The recursive function calculates how many total descendants a fish would have if born on any given day (including itself).
4
u/CrAzYmEtAlHeAd1 Dec 07 '21
Like many, I had to rework part 2 since the brute force method was not going to work. I'm still newer, so I had to get some help from you all, but once I understood the basic concept I was able to throw something together!
Python Part 1 and Part 2
4
u/petercooper Dec 09 '21
Ruby
Not the most efficient solution but because I like to get them very compact..
1
u/Shrugadelic Dec 06 '21 edited Dec 07 '21
Rust
Group the fish by their timer, which can be anything from 0 to 8. The neat part is the
rotate_leftto decrease the timers of each group. Fish with timer 0 will automatically end up at timer 8, and so the only thing left to do is adding another copy with timer 6. Core function:Full code at Github
1
u/Marterich Dec 06 '21 edited Dec 09 '21
It took some time to wrap my head around how to solve this one, but my solution in the end was, to count how many fishes of any given ages exist and then execute the rules on all of them togther Python 3
https://github.com/Marterich/AoC/blob/main/2021/day06/solve.py
1
u/allergic2Luxembourg Dec 06 '21 edited Dec 06 '21
I got in the top 1000 despite taking a break to wake up my kid and start making scrambled eggs, which is pretty good for me. For once, I anticipated the memory/time challenges of the data getting large.
Python
1
u/xMop Dec 06 '21
here's my part b. I didn't do it the smart way for A so it was a rewrite but I came in at rank 2,438 anyway.
1
u/moelf Dec 06 '21
Julia
1
u/ChasmoGER Dec 06 '21
Python3
1
u/rukke Dec 06 '21 edited Dec 06 '21
JavaScript
1
u/zniperr Dec 06 '21 edited Dec 06 '21
python3:
1
u/Cool-Mousse27 Dec 06 '21
Implemented as a linear feedback shift register (LFSR) in Python:
1
u/Un_Gars_Lambda Dec 06 '21 edited Dec 06 '21
Python - 0.24 ms for part 1 and 0.58 ms for part 2
https://github.com/AntoineGanne/adventofcode/blob/master/src/adventofcode/year_2021/day_06_2021.py
1
u/ethercrow Dec 06 '21
Rust
Pretending that a fixed size array is a ring buffer.
3
u/obijywk Dec 06 '21
Python 84/136
Definitely needed to do a performance-improving rewrite between part 1 and part 2 this time :-)
3
u/nthistle Dec 06 '21
Python, 25/4. Finally back on the leaderboard! Helped a lot for part 2 that I had already written it with a dict, so it was literally just changing "80" to a "256" (part 2 split was 0:11).
3
u/captainAwesomePants Dec 06 '21
Python
Love that feeling of optimizing in part 1 and finishing part 2 just by changing the number!
3
u/dizzyhobbes Dec 06 '21
Go 180/1133 :/
All 312 stars!
https://github.com/alexchao26/advent-of-code-go/blob/main/2021/day06/main.go
3
u/meowmeowwarrior Dec 06 '21
python3
I spent way too much time trying to name variables even though there wasn't any problem with the name my mind came up with
3
u/roboputin Dec 06 '21 edited Dec 06 '21
Python3, better complexity than the counter solution.
3
u/Biggergig Dec 06 '21 edited Dec 06 '21
C++
Runs in 40us on a good run
3
u/narrow_assignment Dec 06 '21
AWK
3
u/flwyd Dec 06 '21 edited Dec 06 '21
Raku 7425/4406 (thanks to some really confusing compiler errors about ways that Whatever and lambdas can't be used). MIT license.
3
u/staletic Dec 06 '21
C++20 compile time:
https://godbolt.org/z/Mdvh367nG
3
u/Vastutsav Dec 06 '21
Perl
Please review. Thanks to /u/oantolin's solution I was able to complete this challenge.
3
u/ni3t Dec 06 '21 edited Dec 06 '21
Ruby
This is the part of the competition where I start to feel like a CS impostor again... (heavily golfed)
3
u/Cpt__Cookie Dec 06 '21
Python:
a simple python solution. The rest is just iterating over the days and rewriting the list for 80 or 256 days.
3
u/jagster247 Dec 06 '21
Go day 6. It's a little verbose but you have to remember to map the days, not the fish π GitHub
3
u/sumit_subedi Dec 06 '21
Python3:
3
u/Smylers Dec 06 '21
Perl for both parts:
I was still asleep when the leaderboard was filling up, but I do like that my part-2 time has the same hours and minutes as my part-1 time. The full code has some boilerplate to import
say,sumandany.Today's recommended reading: The Rabbit Problem, a picture book by Emily Gravett. Set in Fibonacci's Field, each page is a month from a calendar, with the rabbits trying to cope with their ever-increasing population. Or watch a primary school teacher read it to you. (βReceptionβ in England and Wales is the school year for children aged 4 to 5.)
3
u/chunes Dec 06 '21
Red
Fun problem today; makes me feel clever haha.
3
u/jayfoad Dec 06 '21
Dyalog APL
3
u/michalopler Dec 06 '21
short Python code for both parts
3
u/sdolotom Dec 06 '21
Haskell
Using a list to count each value 0 to 8, shifting left circularly on each step:
Full code
3
u/SgiathCZ Dec 06 '21
Elixir solution, takes under 50 ΞΌs for part 1 and under 150 ΞΌs for part 2
https://git.sr.ht/~sgiath/advent-of-code/tree/master/item/lib/2021/day06.ex
3
u/royvanrijn Dec 06 '21 edited Dec 06 '21
Java
3
u/Arphrial Dec 06 '21 edited Dec 06 '21
PHP with a bit of sugar to easily read my input. It's not fast but it gets the job done
(~900Β΅s)(~650Β΅s after update).Second revision, reducing 2 tracked lists down to 1 cut the execution time by almost a third!
Nice that parts 1 and 2 just needed the day count adjusting!
3
u/Hairy_Patience_9257 Dec 06 '21 edited Dec 06 '21
Super proud of my solution using Python + matrix multiplications in NumPy, which is considerably fast.
3
u/kmb5 Dec 06 '21
I am a self-taught programmer, not working in dev (marketing automation) so I always struggled with optimizing algorithms. This is my first time that I succeeded in finding a non-brute force way to part2 after first trying with a nice OOP solution for part1. I am so happy!!!
Can anyone tell me the big-O notation for my optimised solution? Is it O(logN)? It cannot be O(1) because it scales with input size (I can do 100k days comfortably but 1M days takes a few seconds), but it also seems faster than O(N).
3
u/imbadatreading Dec 06 '21 edited Dec 06 '21
I used recursion but I ended up have to divide the answer by two and I'm not sure why shrug
Python:
EDIT: Fixed the double counting
3
u/madisp Dec 06 '21 edited Dec 06 '21
A very fast (~5 us) version in Kotlin
3
u/DrugCrazed Dec 06 '21
Typescript solution
Absolutely classic AoC puzzle - regulars will look at it and go "Brute forcing this won't work for part 2" (before going on to brute force it anyway). I wrote a couple of nonsense comments to myself to work out the trick and then converted that into code, then watched as my code had loads of off-by-one errors. After I fixed that it still wasn't quick, so I added the cache and it now runs in under a second for both parts.
3
u/Joao_Nuno64 Dec 06 '21 edited Feb 25 '22
Python instant response time! - Part 1 and 2
My approach was using a dict, where keys were the number of days until a lantern fish creates a new one, and the values were how many fishes were at that same stage.
So, for the initial state provided in the exercise, the dict was:
From now on, all you need to do is decrease 1 at the end of each day and, if it reaches 0, replace it with 6 maintaining the value the 0 had in dict, and increment 8's value in the dict.
Hope it helps :)
Good luck everyone!
3
u/Froggen_Is_God Dec 06 '21
It took me far too long to realise I only one integer list with a length of 9.
PYTHON 3 solution:
import pandas as pd
3
u/cptwunderlich Dec 06 '21
C++
That's a rotate!
https://github.com/cptwunderlich/adventofcode2021/tree/main/day6
3
u/RiemannIntegirl Dec 06 '21
Python 3.9
My solution keeps a list of how many fish are at each of the ages (0-9), rather than keeping track of every individual fish, which would be much more computationally expensive.
3
u/shirleyquirk Dec 06 '21 edited Dec 06 '21
Nim
3
u/LikeRenegades Dec 06 '21
Python
The unrolled dictionary update maybe isn't the nicest, but this still runs in 0.0003 seconds for the 256 day case in naΓ―ve python code.
3
u/ParanoidAndroidQ Dec 06 '21
Haskell dynamic programming:
3
u/chicagocode Dec 06 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
Well, the naive approach works for part one but not part two unless you have a lot of time and memory on your hands. I solved this using a
LongArrayto represent fishies-per-day. If we rotate through it and add the offspring in the appropriate place we can solve this pretty quickly.I used a Long, but if you want to go more than 430 generations or so, you'll have to use a
BigIntegerto represent the gargantuan amount of fishies there would be.3
u/zandland Dec 06 '21 edited Dec 06 '21
C++
Used a sliding pointer, so that
fishes[0]always points to the generation that is about to reproduce, without moving any data. Finishes part 2 in about 700 us on my system.3
u/Ethoxyethaan Dec 06 '21 edited Dec 06 '21
both solutions 148 bytes javascript google chrome console.
3
u/blodgrahm Dec 06 '21 edited Dec 06 '21
Rust
array's rotate_left() helped keep this fast; around 1 to 3 microseconds for each part
https://github.com/natemcintosh/aoc_2021_rs/blob/main/examples/day06.rs
3
u/Laudian Dec 06 '21
Again, quite happy with the solution for today. Especially since I took the "maybe exponentially..." hint and came up with a well readable linear time solution on the first try.
Python 3: https://github.com/Laudian/adventofcode/blob/main/2021/06/day06_01.py
3
u/Ok-Mongoose5168 Dec 06 '21
Python - Dynamic Programming
After a lot of testing in excel, the pattern popped out and I was very happy to create my first dynamic programming solution for this years AOC. Must admit that this puzzle took me a bit longer than I first expected it to.
3
u/kelganor Dec 06 '21
Python
Basically write recursive function, add cache, count input entries and calculate the answer
3
u/LinAGKar Dec 06 '21
Mine in Rust: https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day6a/src/main.rs, https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day6b/src/main.rs
Simple enough, just keep track of the number of fish at each timer state, rather than tracking individual fish. A bit fibonacci-esque. Slight speedup from using a queue rather than an array; not that it matters much since it runs in less than a millisecond anyway, in debug mode.
3
u/codefrommars Dec 06 '21 edited Dec 07 '21
C++
3
u/ActualRealBuckshot Dec 06 '21
Easy peasy Python Solution
I started out with a simple array, but wanted to use the deque structure to avoid slicing or anything else more convoluted.
3
u/flarkis Dec 06 '21
Solution in J. The
power ofverb made things pretty easy today.3
u/lukeredpath Dec 06 '21
Swift: https://github.com/lukeredpath/AdventOfCode2021/blob/main/Sources/AdventOfCode2021/06.swift
Part 1 was easy but not performant enough to tackle Part 2. I have kept both my naive and optimised solutions.
3
u/Vultureosa Dec 06 '21
Python solution with a short class for both parts
3
u/sj2011 Dec 06 '21
I love problems like these - often times I can mentally brute-force my way through it by experimenting and slinging code, but this one required rethinking your mental model of the data. I'll definitely keep this one in mind for future problems and work. Also IntelliJ's intellisense and autocomplete is freaking cool as hell - I had no idea about the Map.merge() method, but it filled it right in. I did need some help from co-workers where we have a slack channel for this event, but that's collaboration and cooperation right? Oh I also wonder if there isn't a mathematical model for something like this...plug it into a formula and off you go.
Here's my Java solution:
3
u/Radiant_Rip_5205 Dec 06 '21
Python 3 solution: https://github.com/kresimir-lukin/AdventOfCode2021/blob/main/day06.py
3
u/InfinityByTen Dec 06 '21
3 Solutions in Rust: Stupid, Big Brain and Sensible
Not proud of my solutions for today by any stretch of imagination. But at least, I decided to put all of them out and be honest about it.
3
u/choco156 Dec 06 '21
Compact & efficient Python 3 solution:
3
u/rlafranchi Dec 06 '21
simple Ruby solution..
https://topaz.github.io/paste/#XQAAAQD/AAAAAAAAAAA0m4poOBCMftdkRQiciXYGFBdGwmQTxpvYqfn/WzgEEWBwIB+mywy2GikxWQ4hPwmjdCcHX1IbJZx2dDAedN9rOh3RcGbDK3JV7hBronMBGj6VS2QHkwELEyBhisBpJmh63t+UIgOPjvVWUdqj6n+VXoSvxc4EshLFWaAoi4O7pSaXXHJYJf8C1pdmYm6VyR8mApbC1gvnlakU/hi35R8wLcYnd5hJcTdY+EVl40jafvwSIEA=
3
u/s0lly Dec 06 '21 edited Dec 06 '21
100 nanoseconds (I think, if QueryPerformanceCounter is working as intended... excluding text parsing code) - using C
Incorporates a nice improvement on how I was doing the code originally, inspired by u/codefrommars
3
u/sojumaster Dec 06 '21
Powershell v5. Part B in 93 Milliseconds!!
I knew I was going to wrong route after Part A took 75 minutes. Re-wrote the code 4 times until I found the turbo button.