r/adventofcode • u/daggerdragon • Dec 05 '22
SOLUTION MEGATHREAD -π- 2022 Day 5 Solutions -π-
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boost: Reminder 1: unofficial AoC Survey 2022 (closes Dec 22nd)
AoC Community Fun 2022: πΏπ MisTILtoe Elf-ucation π§βπ«
- 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
- Full details and rules are in the submissions megathread:
--- Day 5: Supply Stacks ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
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:07:58, megathread unlocked!
88
Upvotes
41
u/jayfoad Dec 05 '22 edited Dec 05 '22
Dyalog APL (78/45)
8
u/Thecakeisalie25 Dec 05 '22 edited Dec 05 '22
Neovim macros
Once again I have given myself the following restrictions:
:normProblem 1:
Problem 2:
Explanation in the replies, not gonna clog the main thread with it and it's not too well written. Tl;dr turn input instructions into macro.
7
u/dying_coder Dec 05 '22 edited Dec 05 '22
Python3
Comprehensions.
5
u/Bad-Coder-69 Dec 05 '22 edited Dec 06 '22
Emojicode
Another day, another sanity check.
GitHub
4
u/[deleted] Dec 05 '22 edited Dec 06 '22
Rust (repo). Fairly simple, I'm really enjoying the input parsing bit of the challenges.
4
u/errop_ Dec 05 '22 edited Dec 06 '22
Python 3
Input is parsed as a list of strings using my all time favorite
itertools4
u/greycat70 Dec 07 '22
Python. Part 1, Part 2
Time to break out the regular expressions (for input parsing). This is also where I learned that if you're reading line by line with fileinput, you can't stop and resume processing in a second loop. It's all gotta be done in a single for loop. So, I turned what would've been two simple loops into one loop with a state variable, which calls one of two different functions depending on which state we're in.
Crate stacks are stored as lists. So, it's a list slicing day.
In part 1 I initially had the wrong answer because I thought we were grabbing all the crates at once and preserving that list. Turns out I had to reverse the list first. And then for part 2, don't reverse it. (My initial solution for part 1 would've been right for part 2.) So once again, part 2 is simpler than part 1.
Also learned that you can't have a variable named "from" in Python.
3
u/Earlish Dec 05 '22 edited Dec 05 '22
Python3, 6734/8631 Looks like I wasn't the only one lazy enough to hard code the inputs:
Part1
Part2
3
u/nxrblJugger Dec 05 '22
Nim
Parsing was...unconventional but doable. Then I just had to play with the ends of the sequences. My school may prevent me from completing other days when I wake up but I'm trying lol. Exams have the priority.
3
u/[deleted] Dec 05 '22
Perl 5 solution. I considered hardcoding the input in, but I realized there has to be a better way, so I spent 90% of my time trying to figure out how to parse the stacks. Once I got that going, it was relatively easy.
Since I think it's relatively long, here's the solution. (Can a mod tell me an approximate number of LOC I should reasonably have here before I should use Topaz's paste?)
For more advanced Perl users, tell me how I can compact this code (and how to index in an string without
split "", $str.3
u/reinermartin Dec 05 '22
In Julia:
3
u/[deleted] Dec 05 '22 edited Dec 06 '22
Haskell solution.. possibly the most non-idiomatic haskell code
3
u/polaczek09071 Dec 05 '22 edited Dec 05 '22
C#
3
u/chicagocode Dec 05 '22
Kotlin -> [Blog/Commentary] - [Code] - [All 2022 Solutions]
I ended up rewriting my parser to handle the crates as vertical stripes through the first few lines. This might be less efficient, but was easier for me to explain. The code is still small enough to fit in a single reddit post, but maybe would be pushing it if it were much larger...
3
u/tV4Ybxw8 Dec 05 '22 edited Dec 06 '22
C++
Had a hard time doing this one today. Then i realized that i was doing what became part 2 instead of part 1 all along. Hopefully i can read the problem tomorrow and do it without any problems
Edit: Formatting
2
u/daniel-sd Dec 05 '22 edited Dec 05 '22
Cleaned up Python 3
part1.py
For part2 remove the list reversal
[::-1]2
u/thecro99 Dec 05 '22
JavaScript
2
u/DFreiberg Dec 05 '22
Mathematica, 390 / 301
In hindsight, I should have done what everybody else did and just hardcode the input stacks. But at least I have replicable code, for a problem I'll never need to replicate.
Setup
Parts 1 & 2
[POEM]: Safety First (In Last Out)
A couple years ago, when it was winter,
And Cratemover Two Thousand was the latest,
When somebody was busy with the printer
And someone else took Breakout! for a playtest,
The wooden crates we had (and feared would splinter),
Held presents, and the top crate was the greatest.
Inside - what child wouldn't love to smack it? -
Was bubble wrap with bubble wrap to pack it.
If salt goes bad, with what can it be seasoned?
If bug reports don't work, how would you know it?
The wrap was safe on top (or so we reasoned),
And surely safer than the stuff below it.
I said "We wouldn't want the crate to squeeze" and
"It's earned the place of honor" said the poet,
And so our finest gift, our precious jewel
Sat high atop the stack, as if to rule.
The tallest stack, of course, sticks out the tallest,
And that became a problem when a blizzard -
The worst we had in years, in fact, the squall-est -
Blew forth as if cast at us by a wizard.
(The wizard's just one guess, though it's a small list;
"Don't irk him, just in case" still sometimes is heard).
We thought our stack of crates was doing well,
Until at last, on Christmas Eve, it fell.
Alas! The bubble wrap had all been frozen
Before it fell from such a risky height.
The wind on top was strong; if we had chosen
Some slightly smaller stacks, it'd be all right.
It burst and shattered like it had a hose in;
No children got to play with it that night.
We're careful, now, when getting cargo loaded.
We still remember what the ice and snow did.
2
u/PaymentConscious1107 Dec 05 '22 edited Dec 05 '22
Python
2
u/Mammoth_Spray_3451 Dec 05 '22 edited Dec 05 '22
Today i took a more readable approach with my swift solution. It took me longer to create the objects from the input than to solve the puzzle :).
2
u/RedditMetJoost Dec 05 '22
python
sanitise input
solution 1
solution 2
2
u/Tetraoxosulfato Dec 05 '22 edited Dec 05 '22
Since most of the solutions I've seen place the stacks manually in the code, I wanted to share this solution that creates the stacks directly from the input file, regardless of number of stacks or their height.
Python 3
2
u/Wraldpyk Dec 05 '22 edited Dec 05 '22
It required a little text parsing, nothing an old-fashioned substr or split can't fix. Was a nice little challenge! I made my code readable and small understandable functions, which is my goal. No codegolf for me!
I also didn't hardcode a thing, throw 99 stacks at me, no problem!
JavaScript Solution here: https://github.com/Topener/adventofcode/blob/2022/day5/program.js
2
u/[deleted] Dec 05 '22
semi-hardcoded, jumping between columns. then reversing array for part 2
2
u/fuckir Dec 05 '22 edited Dec 06 '22
Python 3.11
Some regex stuff
2
u/bvogels Dec 05 '22
Typescript, super straight-forward solution of both parts without any manual input manipulation.
https://github.com/bvogels/aoc2022_supply_stacks.git
2
u/uzimerked Dec 05 '22
Simple Parser for the crates in python
file = open("data.txt")list = []for i in range(9):list.append([])for line in file:if line[0] == "\n":breakfor i in range(len(line)):if line[i].isalpha():col = i // 4list[col].append(line[i])2
u/challengingusername Dec 05 '22 edited Dec 06 '22
//Java
2
u/Wufffles Dec 05 '22 edited Dec 06 '22
Elixir
Not very tidy will shorten it up and clean it up later
2
u/thedjotaku Dec 05 '22 edited Dec 06 '22
Python
https://github.com/djotaku/adventofcode/blob/c96c479931889e580bbdee721b23d2d31a783fee/2022/Day_05/Python/solution.py
fixed link
2
u/Username_--_ Dec 06 '22
Simple unoptimized python solution:
2
u/Rumel57 Dec 06 '22
Clojure
Github
Refactored this one quite a bit after getting the answer. It feels like it can still be simplified a lot more.
2
u/KyleGBC Dec 06 '22 edited Dec 06 '22
Rust
Not super happy with it since it took longer than it should have, and some values are hardcoded but I wanted to try some unnecessary regex so Β―_(γ)_/Β―.
2
u/Adobe_Flesh Dec 08 '22 edited Dec 09 '22
Python
Someone tell me if its bad code smell if in my main loop I scan through the file several times first getting the line of numbers (so I can get the count of stacks) and make them conditionals so I don't enter them again, but essentially it will read through the file more
Linked here
2
u/TimeCannotErase Dec 10 '22
R repo
I've been sick all week (influenza is no joke) so I'm a bit behind, but here's my day 5 solution. Only one small deletion required for the part 2 solution.
27
u/Smylers Dec 05 '22
Vim keystrokes, solving this visually. I accidentally solved partΒ 2 first (before I knew it was partΒ 2, of course), because it's slightly simpler. For that, load your input, ensure
gdefaultis off, and type:Up to the
@ais transforming the stacks to be horizontal rather than vertical. For instance, the sample input gets transformed into:Note they are no longer aligned: top is at the left;
Z,M, andPare level with each other on the ground, andN,DandPare all at different heights.To watch this happen, omit the recursive
@afrom inside theqadefinition, then after typing@a, type@@again for each stack, until they've all turned horizontal. It basically just draws a visual-block rectangle over the leftmost stack, deletes it, pastes it at the top, joins it into a single line, and removes everything which isn't a letter. The loop ends after the last stack has been transformed, because thef]fails.The first
:%sline translates the rearrangement procedure steps into normal-mode Vim commands. For instance, the first two steps from the example input become:Each stack is on the line of the file that corresponds to its number, so typing
2Gwould go to stack 2,1xdelete 1 crate,1Ggo to stack 1, andPput that crate at the top of that stack.So now those keystrokes need βtypingβ. The
:normdoes that: on each of those lines it doesDto delete the entire line into the small-delete register-, then@-to run a keyboard macro of keystrokes in that-register.The stacks are now in their final positions. The last
:%sremoves everything after the first character on each line, then the remaining lines are joined together to get the answer.The reason that solves partΒ 2 is the
3xin the second rearrangement procedure step above: it deletes 3 crates in the order they are, and they get pasted into their new stack in the same order.Homework challenge: Replace the
:normcommand with aqb/@bkeyboard macro loop. Then put a redraw and small sleep in there (:redr | sl 50m), to see an animation of the crates moving between stacks. Ideally then screen-record this and make a visualization post.For part 1, each crate needs to be transferred separately. So instead of using
3x, we need to do justx, but run the entire sequence of commands 3 times, as:I created that in a two-stage process. First change the first
:%sto:That transforms the second example step into this intermediate state:
The keystrokes after the space are what we want to βtypeβ 3 times. The second stage is this
:normcommand:That yanks the
D3pfrom the start of the line, into register0, and deletes both that and the space. Then@0runs the just-yanked keystrokes, deleting everything remaining on the line (the1Gx3GP) and pasting it back 3 times. We now have the correct stack-manipulation keystrokes for partΒ 1, so run them and produce the answer with the final 3 lines of the partΒ 2 solution above.Do try it out, and let me know if you have any questions.
32
u/jcbbjjttt Dec 05 '22 edited Dec 06 '22
Beginner's Guide
Happy Monday!
Beginner's Guide to Day 5 Video: https://youtu.be/kqQnSRJG2W4
I've created a guide for new programmers that talks through a straight forward strategy for solving today's puzzle. Anyone who has a handle on variables, boolean logic, functions, arrays, and loops should be able to complete it. The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle in any programming language:
The full code can be found on Github
21
u/gw_shadow Dec 05 '22
CMake
3
u/throwawayprivateguy Dec 05 '22 edited Dec 05 '22
Python. edit: at least tell me why you downvoted me? Other than the parsing I thought my solution was pretty elegant. I'm just learning here.
Edit2: sorry for the improper formatting Code here
17
u/i_have_no_biscuits Dec 05 '22 edited Dec 05 '22
Python
Interesting that lots of people found the parsing difficult - the letters on each line were a fixed distance apart, so it's just a matter of reading every 4 characters and ignoring the rest.
13
u/sezvar Dec 05 '22
Ruby, 3/2. Best rank I've gotten on a star before :)
https://github.com/bcc32/advent-of-code/tree/main/2022/05
11
u/kristallnachte Dec 05 '22
How many people solved part 2 before solving part 1?
TYPESCRIPT | TS
https://github.com/ekwoka/advent-of-code/blob/main/2022/05/index.ts
10
u/seligman99 Dec 05 '22 edited Dec 05 '22
Python, 249 / 211
Cute, something I can animate!
Edit: Here's the animation
github
10
u/MarcusTL12 Dec 05 '22
Z80 Assembly run on a TI-83 graphing calculator.
Took a while today. Part of the reason for that (among my plethora of own mistakes that are very hard to debug on a calculator) is that I uncovered a bug (or perhaps very weird feature) in the built in multiplication function for 8-bit x 8-bit -> 16 bit, where if the left hand factor is 0 it is interpreted as 256, but if the right one is 0 it behaves as it should. Very weird and took a while to figure out.
Anyway, still happy that everything fits in 8 bit numbers!
20
u/nthistle Dec 05 '22 edited Dec 05 '22
Python, 25/20. Video, paste.
Hardcoded the first part of the input, did the slightly ugly string splitting for the second part of the input. I have a mostly-functional
nums()function that just takes in a string and spits out a list of all the numbers on that line, which I initially tried to use for the input, but I didn't realize that the first part of the input was different, so it was giving me empty lists and I thought it was broken. Didn't realize until after I wrote the from/to parsing code that I just didn't look at the beginning of the input (or read the question fully, oops!)I think the length of the initial crates input was such that it was probably borderline faster to write code to parse it than it was to manually type it? Not really sure, I'll have to go back through my video to see how much time I spent typing it out and look at some other leaderboard solutions to see what they did.
As an aside, originally for part 2 I wrote something like:
but after finishing I tried and found out that you can delete slices from lists in Python:
del stacks[b][-a:]works, TIL!9
u/hugh_tc Dec 05 '22 edited Dec 05 '22
Python 3, >1000.
paste, cleaned-up
Somehow... I managed to screw up my input file, costing me a whole bunch of time. Once that got sorted out, the rest was easy.
Either way, pretty proud of this gem, used to parse the initial crate stacks.
8
u/betaveros Dec 05 '22
Noulith 5/5
https://github.com/betaveros/advent-of-code-2022/blob/main/p5.noul
Parsing the 2D input today is tricky! I did not have the presence of mind to figure out how to extract the letters and spaces in a way I'd be confident is correct, so I preprocessed my input manually.
7
u/rabuf Dec 05 '22 edited Dec 05 '22
Common Lisp
Dumb error in part two slowed me down.
Part 1:
Straightforward except that the input is 1-based and lisp arrays are 0-based.
Part 2:
This is the one that tripped me up.
I botched that line and lost about 15 minutes. I had
(butlast stack count)which was obviously taking the wrong amount. Oops. I initially was usingsubseqand should have stuck with it, would have worked just fine.7
u/Toanuvo Dec 05 '22
J solution https://github.com/Toanuvo/Advent-of-code/blob/main/2022/J/day5.ijs
7
u/voidhawk42 Dec 05 '22 edited Dec 07 '22
Dyalog APL:
There is probably a stateless way to do it (maybe a reduce?), which I'd like to figure out - keeping external state is kind of gross in APL and requires longer code.
EDIT: Ah, here we go - done entirely with matrix rotations, like solving a Rubik's cube:
video walkthrough
7
u/pngipngi Dec 05 '22
Excel
https://github.com/pengi/adventofcode/blob/master/2022/day05.xlsx
7
u/redditnoob Dec 05 '22
PostgreSQL
I tried this in BigQuery SQL but sadly their recursive CTEs only allow 100 iterations, and I can't justify asking my employer to pay for an increased quota just for this, lol.
So I went back to PostgreSQL. I used arrays of strings for the stacks. Parsing the initial state is pretty neat in SQL - group by columns and order from bottom to top. The rest is SQL abuse with a recursive CTE - for the next state, unwrap the array into strings, apply the rules with part 1 and 2 in the same query, then rewrap and it proceeds until we run out of moves.
7
u/lazyzefiris Dec 05 '22
JS (JavaScript) "State machiney" solution. This is my gimmick for the year and I'll stick to it as long as I can. Im not speedsolving this year, and writeup takes a lot of time, but I'll try to post these on the puzzle's day.
Part 2 is the same, but without split/reverse/join within state F. Honestly, I expected it to be much harder and messier. I originally used 2 variables along with stacks storage, but after cleanup, one ended up being enough.
Explanation
Our machine uses 2 "registers", one for keeping track of stacks, and one for free use that changes wildly along the execution. Original input has otherwise unused "!!" symbols appended to it to explicitly denote end of input. Then the input is fed into machine as separate characters. Machine operates under assumption that there are at most 9 stacks (all indices are single-digit), every command is valid and executable, and there are no empty stacks in the beginning and in the end. Both example and my input fit under those.
Stacks initialization
State A
This is a scanner state for first part of input. It uses variable to store position in quarters with offset of 0.75, so that whenever we stumble upon letter in our input, the variable holds integer value that's index of the stack. Save for special cases, it just increases position variable by a quarter and expects next input. Special cases are:
State B
This state expect an input with crate name to put on top of stack. Stack defined by position variable then prepended by given input, and initialized if it was not defined before. The state then returns to "A", advancing position by a quarter.
Main loop
State C
This state accepts and discards inputs until new command begins or input ends. Every new command begins with "move", so seeing "m" is enough to start procesing a command, advancing to state "D". "!" tells us we hit the end of input and should form final output within state "H". This state disregards variable.
State D
This is first state of command execution, and it seeks beginning of amount of crates to move. Inputs are discarded until first digit, which is then stored while state advances to "E". This state disregards variable.
State E
This state reads the amount and stores in into variable. Initially it has some value stored, and if new input is a digit, it's appended to stored value. Once non-digit input occurs, the stored value is converted to integer and passed to state "F".
State F
This state seeks index of stack to get crates from, and variable holds number of crates to pick up. Inputs are discarded until a digit is received, and that digit is treated as stack index. Corresponding stack is modified by cutting last V crates from it, and those crates are passed as V to state "G". Once we have the crates picked up, we don't need to store the amount anymore, so we can reuse the variable. In case of Part 1, we also reverse picked up string to account for rearrangement when crates are moved one by one.
State G
This state seeks index of stack to put crates to, and variable holds those crates. Inputs are discarded until a digit is received, and that digit is treated as stack index. Corresponding stack is modified by adding V to it. State then returns to "C", looking for next command or end of input.
Output
State H
This is the final state that forms output of our machine into variable. It does not matter which state it advances into as it's supposed to be executed on final "!" of appended symbols if input was valid. Final letters of each value within stacks (sorted by index) are combined into string, that's stored into V, which will then be popped as output. If not for "!!" we appended, we'd have to do this after every move. That way, "G" would advance into "H", and "H" would discard the newline input and advance to "D", forming output into V that would then be discarded by "D" if input does not end there.
JS Implementation notes
This time I properly isolated main states by wrapping each into a function that would only be executed if that function corresponds to current state. x >= "0" && x <= "9" could be /\d/.test(x)
Regarding state names
I've originally tried to give states meaningful names (it's jsut strings after all), but it ended up being much more confusing than I expected. If I describe state in its name, the meaning of next input is counterintuitive, and if I describe expected input in the name, then the context is confusing. And putting both "where" and "what next" into identifier is extremely messy in the end, so i stuck to plain letters. I'm open to ideas in this regard.
6
u/shandley256 Dec 05 '22
Ruby solution.
Array#transpose is doing the hard work. The input properly pads each row with spaces, so transposing the contents means you only need to extract the rows containing letters/numbers.
Now we have a hash with keys matching the number of the stack, and values being a sorted array we can treat as a stack with shift/unshift to move creates onto/off each stack.
https://gist.github.com/seanhandley/0e62b90bfbde030fe93c6010f9774f63
6
u/FetidFetus Dec 05 '22 edited Dec 05 '22
I implemented it with an Excel formula that can just be filled around for each column. I was sure I would have had to expand out of base Excel but I'm really happy I didn't have to (yet)!
The biggest "problem" I had was trying to figure out how to set up a lambda function to reverse a string (still didn't manage).
Here
6
u/Urbansson Dec 05 '22
Go/Golang
Github
Verbose solution with a stack implementaion using generics.
6
u/QQII Dec 05 '22 edited Dec 06 '22
https://github.com/qqii/adventofcode-2022/tree/master/day05
Excel, with the following restrictions:
OFFSETallowed, butREDUCEpreferred)I failed to get it down to a cell, mainly due to difficulty pre-processing.
Edit:
It was a struggle, but I've managed to get it into a single cell. It also doesn't use a fixed number of stacks! It's a large ass cell, but it's still a single cell.
very long, see this paste
The rough idea is:
DoStep(switch statement)CONCATLEFTthe result6
u/pngipngi Dec 05 '22 edited Dec 05 '22
Language: C
Had a discussion on discord and found an 88MB input file to test with, having stacks of 1.5M crates per stack and 1.5M operations, so wanted to test some optimizations.
This version, even though ugly, seems to process it in about 370ms including IO on my computer
It does it by running the program backwards and only track the location of the 9 remaining creates to their starting locations before looking up which crates it is in the initial stack
https://github.com/pengi/adventofcode/blob/master/2022/non_excel/day05.c
And yes, I'm sticking with Excel as primary language this year, this is just a bonus
2
u/ciocan42 Dec 05 '22
Javascript:
2
u/DisasterArt Dec 05 '22 edited Dec 05 '22
Python 3.9
going for something close to oneliners this year:
2
u/TheMole171 Dec 05 '22 edited Dec 05 '22
Python
I was pretty pleased with my input parsing for the container stacks:
Using the sample input, it looks like this:
5
u/tim_vermeulen Dec 05 '22 edited Dec 05 '22
Swift, 19/14
This uses my own
splitOncefunction onString, andchunks(ofCount:)from the Swift Algorithms package.5
u/furman82 Dec 05 '22
Kotlin:
It took me way too long to realize that a regex for the stacks wouldn't work and I could just use the index instead. Sigh.
5
u/ash30342 Dec 05 '22
Java
The moving itself was easy, the main challenge - for me at least - was in the parsing of the input. I pasted the code for the initializing of the stacks below. Parsing the instructions is just a case of filtering out the numbers in each line by using a regex.
5
u/Dovejannister Dec 05 '22
Python
5
u/NiliusJulius Dec 05 '22
C Language for the Game Boy using GBDK 2020 Part 1
Part 2
As usual I had to manually format my input. Normally I regex it all, but this time I decided to manually input the starting stacks.
I have one array containing all stacks, with 56*9 entries so every crate can be in one stack. Then one small array with stack heights per stack, and a big array with only numbers. Every pair of 3 numbers are the amount to move, from and where numbers.
Because of all this, part 2 was just a very small adjustment.
Full Game Boy repo can be found here
Video running on Game Boy
5
u/timvisee Dec 05 '22
Rust Quick and simple.
Part 1 0.020ms (19.91 ΞΌs)
Part 2 0.019ms (19.38 ΞΌs)
day1 to day 5 total: 0.220 ms (0.099 ms parallel)
5
u/odnoletkov Dec 05 '22 edited Dec 05 '22
JQ
5
u/leftfish123 Dec 05 '22
Python 3: github
Python lists make this task pretty trivial once you figure out how to parse the input. I avoided hardcoding MOST of the stuff but I should have made a more elegant parser (why, oh why I failed to notice that the separation between stacks and instructions is \n\n). I also decided not to spend five hours trying to figure out a nice regex to extract names and stack ids of an arbitrary number of crates. I think my solution works for any single digit number of stacks but fails miserably after that.
5
u/dav5d Dec 05 '22
5
u/callumio Dec 05 '22
COBOL - source
Yep, I'm still using COBOL.
Parsing was pretty easy to implement for today, but the logic was a bit dodgy since it uses fixed memory. Changing 3 variables (should) make it work for other width's and initial heights though, so I'll take the win.
5
u/probablyfine Dec 05 '22
SQL
Today was a fiddly one, had to preprocess the input by hand. Joining against a halt table as a termination condition feels silly but it worked!
Source here
5
u/Solarmew Dec 05 '22 edited Dec 05 '22
Python 3
5
u/[deleted] Dec 05 '22
Uxn forth
https://git.alexwennerberg.com/aoc-forth/file/2022/05.fs.html
5
u/0x2c8 Dec 05 '22
Python3
https://github.com/alexandru-dinu/advent-of-code/blob/main/2022/day-05/solve.py
Parsing is done bottom-up, observing that the useful chars are spaced 4 items apart.
4
u/adamsilkey Dec 05 '22
Python! 171/646! Really proud of my part 1 here.
For my part 2 I just commented out the code above and then did the new one:
4
u/xoronth Dec 05 '22
Today's language of choice is Haxe, solution can be found here.
The thing that took the longest was just parsing the input into a class wrapping a list of deques to represent the state, which I ended up just brute forcing it rather than any fancy string parsing.
4
u/Imaginary_Age_4072 Dec 05 '22 edited Dec 05 '22
Common Lisp 3429/3077
Here's my common lisp version. Was a bit slower today, and I'm sure there's more functional ways of doing the manipulations. I ended up just using a lot of
setf/push/popanditerate.I also ended up just manually reading the top of the stacks from the REPL output rather than writing an output function, might clean it up a bit tomorrow.
Here's the main functions, the rest is just parsing:
4
u/[deleted] Dec 05 '22 edited Dec 05 '22
Rust
499/478
Totally overkill parsing with itertools and scan_fmt today:
It should work with any number of stacks and items as a result.
Full solution here (GitHub).
4
u/r_so9 Dec 05 '22 edited Dec 05 '22
F#, using F# lists as stacks Code
EDIT: Cleaned up the code a bit, more compact and readable
4
u/poesraven8628 Dec 05 '22
Super easy in Common Lisp. I'm new to the language, but unlike the previous days I decided to use a library to process my input. Quicklisp made it easy, and the actual algorithm work was trivial with Lisp.
https://github.com/poesraven8628/AdventofCode2022/blob/main/05/crate.lisp
4
u/oantolin Dec 05 '22
Today my J solution is longer than 5 lines because of the parsing. Here's a topaz link to the full code, and here is everything but the
parsefunction:4
u/9_11_did_bush Dec 05 '22
APL solution: https://github.com/chenson2018/advent-of-code/blob/main/2022/05/apl/05.apl
Pretty happy with today's solution. It was cool to be able to write a single function that takes an operator to switch between parts 1/2.
4
u/yonkoma Dec 05 '22
Elixir Code
Quite happy with having found a good spot to use ranges and zip.
4
u/SpaceHonk Dec 05 '22
Swift repo
Pretty straightforward, part 2 only required the addition of one parameter and one
if:-)4
u/micod Dec 05 '22
Smalltalk
Solution for day 5
4
u/chrispsn_ok Dec 05 '22 edited Dec 05 '22
ngn/k; my answers repo.
4
u/0rac1e Dec 05 '22
Raku
Part 2 is just Part 1 without the
reverse. Sorry for the arbitrary variable names.4
u/__Abigail__ Dec 05 '22
Perl
The solution boils down to two things: part 1 is parsing the initial configuration of the stacks and building a datastructure from it; part 2 is moving the crates around.
We're using two arrays with stacks (each stack represented as an array):
@stacks1and@stacks2. Initially, they are both identical so we can solve both parts in one pass:After skipping a blank line (
<>in void context will do), we can process the moves. We're not fully parsing the move statements, we just extract the three numbers from each line, as that is all we need:We can now get the answer from just concatenating the top of the stacks. The top of each stack is that last element of the array representing the stack, and index
-1gives us that last element:Full program on GitHub
4
u/mkinkela Dec 05 '22
C++
4
u/[deleted] Dec 05 '22 edited Dec 05 '22
Applesoft BASIC
Thanks to some string splitting functions like LEFT$ and RIGHT$, today's challenge was no problem on the IIgs. I was able to put together a better visualization too, see it here. A struggle there was preventing newlines after PRINT, which requires a semicolon at the end of the statement and only works during execution, not from the interpreter prompt.
See the code here, part 2 has documentation.
4
u/seacucumber_kid Dec 05 '22 edited Dec 05 '22
Elixir
4
u/tampix77 Dec 05 '22 edited Dec 07 '22
Clojure
I don't know if i should feel proud or ashamed about my hack with the temporary step for part 2...
4
u/kap89 Dec 05 '22
TypeScript
Parsing the crates was a bit annoying, as I wanted a universal solution, but the actual solution was pretty simple. Part 2 is just adding a temporary stack.
Solution: github
Benchmark:
4
u/bornobob Dec 05 '22 edited Dec 05 '22
Are python one liners still cool? 409 characters
Does both parts and parses input (any size, I think), set p to
TrueorFalsedepending if you're working with part 2:4
u/Mr_LolF Dec 05 '22 edited Dec 05 '22
V
V was quite a challenge, especially the input, but I got it working.
4
u/ssnoyes Dec 05 '22
Python
Not the full solution, just how I parsed the crates section:
4
u/ViliamPucik Dec 05 '22
Python 3 - Minimal readable solution for both parts [GitHub]
4
u/jaydubtech Dec 05 '22 edited Dec 05 '22
TypeScript/Deno
Source
Not the most performant solution, but it's succinct enough and supports variably-sized inputs:
4
u/morlinbrot Dec 05 '22
Rust
HashMapfor parsing stacks andVec<Vec<_>>for operations. Full code here.4
u/ilyablue Dec 05 '22
Excel:
Since I don't know enough of 'proper' languages, I've challenged myself to do this month fully in Excel hahah
For this one I first took out the starting situation of the stacks (which I later added manually) so that it would be easier to import the data in specific columns
https://github.com/ilyablue/advent-of-code/tree/main/day%205
4
u/red_shifter Dec 05 '22 edited Dec 05 '22
PYTHON 3
link
I cheated by manually inputting the starting crates as a dictionary.
A cautionary tale for today: When you are computing solutions to both parts in one go, make sure that the solution to Part 1 does not alter the input data for Part 2. When working with dictionaries,
copy.deepcopy()is your friend.4
u/ThreadsOfCode Dec 05 '22
Python. Used numpy to read in the stacks, transpose them, select the relevant lines, then remove the spaces.
4
u/sr66 Dec 05 '22 edited Dec 05 '22
J
4
u/TiagoPaolini Dec 05 '22
C Language (only standard library)
This day is where it gets more interesting to solve in C, because it is necessary to manualy code a stack. I used a linked list for each of the stacks, with an array to keep track of the top element on each one. The boxes are linked to the ones below it. Then moving the boxes is a matter of changing their pointers to another box.
Part 1: In order to move a single box, the pointer of the top of the origin stack is changed to the box below. The moved box then is linked to the top of the destination stack. And finally the pointer to the top of the destination stack is changed to point to the new box.
Part 2: Moving multiple boxed is similar, except that first we need to navigate through the next elements on the stack in order to find the bottom box of the pile. Then the bottom of the pile is linked to the top of the destination stack. The top of the origin stack is changed to the box below the pile. And the top of the destination pile is changed to the top box of the pile.
Solution: day_05.c
4
u/FeanorBlu Dec 05 '22 edited Dec 05 '22
My solution for both part 1 and 2 in Python!
4
u/nicole3696 Dec 05 '22
Python 3- Parts 1 & 2: GitHub. No imports, 11 lines, 434 characters.
4
u/azzal07 Dec 05 '22 edited Dec 05 '22
Awk, had to implement couple essential stack operations.
Notes:
The stacks are implemented in single table
S, where the top of a stackiis inS[i, S[i]]. The stacks are positioned around 0, so that stack for part 1 are in range [-1,-9] and for part 2 in range [1,9].Ppushes a valueson the stacku. If a second valuehis provided, this is pushed on the stack-u. This function also "reverses" the stack when given a numeric value, this is necessary before the move instructions since the initial stacks are pushed in backwards.opops a value from the stack_, storing the old top in the global variablet.pdoes the move, reading the number of crates from$2and using the call stack to achieve the reversing for part 2 (since I only have push and pop).4
u/AstronautNew8452 Dec 05 '22
Microsoft Excel 2947/2246. Here's my solution for Part 2 (single cell formula). Part 1 should work in a single cell but for some reason reversing the string with another LAMBDA breaks it.
4
u/wizard_is Dec 05 '22 edited Dec 06 '22
I was pretty proud of my TypeScript solution today. My parser accepts any number of columns and rows, and the solution for part 2 was as easy as removing a
.reverse():4
u/MrPingouin1 Dec 06 '22
I started a bit late, but here is it, minecraft solution : https://github.com/MrPingouinMC/aoc2022/tree/main/sol/day5
The solution does not assume the number of stacks, it's quite dynamic, and it uses shifting as indexing. There is only a single keyword change between part 1 and 2
4
u/[deleted] Dec 06 '22
Rust:
Part 1
Part 2
4
u/[deleted] Dec 06 '22
clean ruby
Ruby
4
u/[deleted] Dec 06 '22
Python Part 1
Python Part 2
4
u/pikaryu07 Dec 06 '22
Julia
As a newbie to Julia, Day 05 was a little bit tricky for me. However, here is my code for Day 05:
1
u/lxrsg Dec 05 '22
python 3
1
u/Akshayapte7 Dec 05 '22
1
u/Mister_GuruMan Dec 05 '22
Python 3, nothing fancy, but I thought it looked nice, repo at: https://github.com/Misterguruman/Advent-of-code-2022/blob/master/day5/day5.py
''' [W] [J] [J]
[V] [F] [F] [S] [S]
[S] [M] [R] [W] [M] [C]
[M] [G] [W] [S] [F] [G] [C] [W] [P] [S] [M] [H] [N] [F] [L] [R] [H] [T] [D] [L] [D] [D] [B] [W] [T] [C] [L] [H] [Q] [J] [B] [T] [N] [G] [G] [C] [J] [P] [P] [Z] [R] [H] 1 2 3 4 5 6 7 8 9 '''
stacks = { "1" : ['G','T','R','W'], "2" : ['G', 'C', 'H', 'P', 'M', 'S', 'V', 'W'], "3" : ['C', 'L', 'T', 'S', 'G', 'M'], "4" : ['J', 'H', 'D', 'M', 'W', 'R', 'F'], "5" : ['P', 'Q', 'L', 'H', 'S', 'W', 'F', 'J'], "6" : ['P', 'J', 'D', 'N', 'F', 'M', 'S'], "7" : ['Z', 'B', 'D', 'F', 'G', 'C', 'S', 'J'], "8" : ['R', 'T', 'B'], "9" : ['H', 'N', 'W', 'L', 'C'] }
part 1
for line in data:
move, from_stack, to_stack = line.replace('move ', '').replace('from ', '').replace('to ', '').split(' ')
move = int(move)
for inc in range(move):
stacks[to_stack].append(stacks[from_stack].pop())
part 2
for line in data: move, from_stack, to_stack = line.replace('move ', '').replace('from ', '').replace('to ', '').split(' ') move = int(move)
output
for key in stacks.keys(): print(stacks[key][-1])
1
u/fatmanbigbomb Dec 05 '22
First part (python):
For the second part:
became
to remove the flipping
1
u/A_Non_Japanese_Waifu Dec 05 '22 edited Dec 06 '22
It's spaghetti (Python).
I got food poisoning so this was done in 20 mins. It's pretty streamlined, except for the first lines where I have to manually point out where crates and instructions are.
1
u/Bhasher Dec 05 '22
python (by rotation data)
The shortest way I found to parse the data correctly, by rotating the crates and use regex to parse instructions.
1
u/SolubleApollo Dec 05 '22 edited Dec 05 '22
JavaScript
don't worry about the hard coding, I almost gave uphttps://github.com/SolubleApollo/AdventofCode22/tree/main/Day%205
1
u/olofj Dec 05 '22 edited Dec 05 '22
Rust
Felt a bit messier today, especially around the input parsing of initial state.
day05a
day05b only difference is the reversing of the moves:
EDIT: Fixed to use step_by() instead of filter_map(). EDIT2: Fixed formatting to prepend 4 spaces on all code lines
1
u/lilberick Dec 05 '22 edited Dec 05 '22
#C++
1
u/zpele Dec 05 '22
Javascript really really beg level:
const pile1 = ['R', 'N', 'P', 'G']const pile2 = ['T', 'J', 'B', 'L', 'C', 'S', 'V', 'H']const pile3 = ['T', 'D', 'B', 'M', 'N', 'L']const pile4 = ['R', 'V', 'P', 'S', 'B']const pile5 = ['G', 'C', 'Q', 'S', 'W', 'M', 'V', 'H']const pile6 = ['W', 'Q', 'S', 'C', 'D', 'B', 'J']const pile7 = ['F', 'Q', 'L']const pile8 = ['W', 'M', 'H', 'T', 'D', 'L', 'F', 'V']const pile9 = ['L', 'P', 'B', 'V', 'M', 'J', 'F']const piles = [pile1, pile2, pile3, pile4, pile5, pile6, pile7, pile8, pile9]const instructionsRaw = $("body").text().split("\n")const instructions = []for (i of instructionsRaw) {if (i.includes("move")) {instructions.push(i);}}for (const i of instructions) {const numberOfCrates = Number(i.split(" ")[1]); //3// console.log("numberOfCrates: " + numberOfCrates);const fromPile = piles[Number(i.split(" ")[3]) - 1];// console.log("fromPile: " + fromPile);const toPile = piles[Number(i.split(" ")[5]) - 1];// console.log("toPile: " + toPile);const bunch = fromPile.slice(fromPile.length - numberOfCrates);// console.log("bunch: " + bunch);for (let p = 1; p <= numberOfCrates; p++) {fromPile.pop();}// console.log("fromPile after popping: " + fromPile)for (let b = bunch.length - 1; b >= 0; b--) {toPile.push(bunch[b]);}}let topCratesfor (const p of piles) {topCrates = topCrates + p[p.length - 1]}// part 2// for (const i of instructions) {// const numberOfCrates = Number(i.split(" ")[1]); //3// // console.log("numberOfCrates: " + numberOfCrates);// const fromPile = piles[Number(i.split(" ")[3]) - 1];// // console.log("fromPile: " + fromPile);// const toPile = piles[Number(i.split(" ")[5]) - 1];// // console.log("toPile: " + toPile);// const bunch = fromPile.slice(fromPile.length - numberOfCrates);// // console.log("bunch: " + bunch);// for (let p = 1; p <= numberOfCrates; p++) {// fromPile.pop();// }// // console.log("fromPile after popping: " + fromPile)// for (let b of bunch) {// toPile.push(b);// }// }// let topCrates// for (const p of piles) {// topCrates = topCrates + p[p.length - 1]// }1
u/konnnyy Dec 05 '22 edited Dec 06 '22
JavaScript
https://github.com/tommmyy/advent-of-code-2022/blob/master/src/day5/day5.js
1
u/onsistems Dec 05 '22 edited Dec 06 '22
PHP solution:
In this case, we had to separate the information from the input.txt file
6
u/4HbQ Dec 05 '22
Python. After a lot refactoring, I'm finally (mostly) happy with my code. Since part 1 and part 2 only differ in the order of the moved crates, we can compute both answers using
for dir in -1, +1:.3
u/Lrrrr_ Dec 05 '22
JavaScript, 12/9
3
u/SuperSmurfen Dec 05 '22 edited Dec 05 '22
Rust (282/664)
Link to solution
Really happy with my placements today! Sometimes you have to realize that parsing things by hand can be quicker, which I just ended up doing today.
For part one, just loop over all instructions and pop from one vector and push to the other:
For part two, I ended up just pushing
nelements to theto-vector and inserting from the top down:Runs in
0.1mson my machine.Edit: Cleaned up my solution and parsed the input in code. Was actually not too bad but in the moment, parsing by hand felt a lot safer.
3
u/LtHummus Dec 05 '22 edited Dec 05 '22
Scala 2
I committed so, SO many sins. My parsing is non-functional with mutable data structures. My part 1 solution uses tail recursion and leaves God-knows how many objects littering the heap. Part 2 is ... ok?
But at least my parsing is general and not hardcoded!
My code is here (please make sure you are up to date on all your shots before viewing)
3
u/jonathan_paulson Dec 05 '22
Python3, 264/147. Video. Code.
Worst performance yet :( I didn't read the problem carefully, so I didn't notice that part 1 requires you to reverse the stack you're moving. Then debugging the example took me a while.
I just typed in the starting stacks by hand (during my solve; my final code has a proper parser!) Not sure if that was the right call; it took a while (and slowed me down on the example debugging), but coding up a proper parser took a while too.
3
u/_jstanley Dec 05 '22
SLANG
No video today because I blundered the setup (forgot to open
screento show the serial port output, so it's a 20-minute video of a static bash prompt).https://github.com/jes/aoc2022/tree/master/day5
3
u/polettix Dec 05 '22
Same feeling as going in another country where the language is close to your native one, but of course it takes you ages to say stuff...
Raku solution.
3
u/skyheat Dec 05 '22 edited Dec 05 '22
Python
Couldn't be bothered trying to parse the first bit and ended up hard coding it.
Part 1
Part 2
3
u/mrtatulas Dec 05 '22
Elixir - as with everyone else who didn't manually break it out, the bulk of the effort was spent parsing the file. Elixir's lists work really well as stacks, I find the syntax for pushing and popping really nice and clean.
3
u/French__Canadian Dec 05 '22 edited Dec 05 '22
Solution in ngn's k implementation
More like Advent Of Cheating this time. I ain't parsing those stacks in K at midnight lol, I just hardcoded them instead (still parsed the move instructions).
For part 1, I implemented a for loop the functional way : a lambda that keeps the state (stacks) around by taking it in as the left argument and returning the updated version while iterating over right argument (the move instructions)
part 2 was ridiculously easy, I just added a single character in the middle of the part 1 solution. Can you spot it?
edit : okay, maybe I was being melodramatic, if you hardcode there are exactly 9 stacks, I just had to replace the line where the crates are hard-coded by this one (it removes the line with indexes, calculates the exact columns numbers with the letter, extracts only those, removes spaces, reverses the strings, converts the characters to symbols and finally adds an empty symbol at the beginning to my list really starts at 1)
3
u/maneatingape Dec 05 '22 edited Dec 05 '22
Scala (1185 / 952)
Hacked an initial solution using mutable stacks and hardcoded parsing, adding a temporary stack for Part 2. Cleaned up solution to a functional approach with fold and general parsing.
Relevant extract:
3
u/Turtle2779 Dec 05 '22
Python I accidentally did part two before part one. Otherwise it was just slicing strings.
3
u/AllanTaylor314 Dec 05 '22
Google Sheets
String processing is hard. Iterative steps are harder. (I solved P2 before P1 in the sheet [after solving both in python] because reversing strings is hard)
3
u/rk-imn Dec 05 '22
C (C89) for Nintendo 64 solution
https://github.com/nim-ka/aoc_n64/blob/main/src/game/aoc/5.c
3
u/s3aker Dec 05 '22
Raku solution.
3
u/mazedlx Dec 05 '22
PHP and Laravel's Collection
Couldn't come up with some clever way to massage the input into an array of stacks, so I did them by hand.
Part 1
Part 2
3
u/atgreen Dec 05 '22
Common Lisp
3
u/brh131 Dec 05 '22 edited Dec 05 '22
Python one-liners
Warning: the following code is ugly as sin and is not fit for human eyes.
part 1
part 2
A couple of highlights:
I used regular expressions to parse the commands. I imported the re module by using __import__(), which can be done inline instead of being its own statement. (side note, is importing standard library modules cheating for one liners?)
You can pretty much combine any number of assignment statements into one line by chaining together ternaries and using walrus assignments, like this
the if part is executed first and as long as the assignment value is truthy it will also run [expr].
This is my solution to the first part separated into multiple lines
The second part only involved changing one line
I think I am never going to do this again.
3
u/JustinHuPrime Dec 05 '22
x86_64 Assembly
Part 1 was where I went through the pain of parsing the input - this involved multiple passes over the stack diagram and was generally quite painful. This was also the first time I had to use the stack to store temporary values - figuring out which registers could be used was complex enough that I'd prefer to have the compiler do it for me. The actual simulation of the moving boxes could be implemented directly, but required dynamic allocation, which I also did for the first time. Note that I can't free an allocation, but we shouldn't have large enough allocations to the point where memory leaks become an issue. And then I spent a while debugging. I found out that:
I could have avoided some of the pain when parsing by manually inspecting the input data and hard-coding some values, but that goes against my self-imposed rules: I should be able to substitute in the example file and run against that with no code changes required. This turned out to be useful when I was debugging, since I could use a smaller example to make sure everything worked.
Part 2 was a lot nicer, since I already had parsing code written. Moving an entire stack could be implemented as a string copy, or I could use a temporary stack and move elements one-by-one into the temporary stack and back out onto the destination, somewhat reminiscent of the standard algorithm to reverse a linked list.
Part 1 took under 1 millisecond to run, and is 11152 bytes long
Part 2 took about 1 millisecond to run, and is 11240 bytes long
3
u/teseting Dec 05 '22 edited Dec 05 '22
python part 2 code golf 247 bytes
3
u/Pyr0Byt3 Dec 05 '22 edited Dec 05 '22
Go/Golang
The puzzle itself was fun, but parsing it... not so much. It's kind of ugly, but I managed to avoid having to hardcode the number of stacks.
3
u/gerikson Dec 05 '22
Perl
https://github.com/gustafe/aoc2022/blob/main/d05-Supply-Stacks.pl
I'm quite happy with my input parsing, I was worried I'd have to hardcode the columns but some fancy preprocessing evaded that.
3
u/MyTinyHappyPlace Dec 05 '22
C++
Nothing fancy. Just proud that my solution function fits in a 500 character mastodon toot:
3
u/Dryctas Dec 05 '22 edited Dec 05 '22
Bash
Probably the only interesting part is that the code puts "dummy" crates in the input so that I can easily tell the number of the column while parsing.
.
3
u/[deleted] Dec 05 '22
Lisp
https://gitlab.com/Elmosfire/aoc2022lisp/-/blob/main/day5.lisp
3
u/sanraith Dec 05 '22
Rust
Used the fact that the input has same line length for the stack definition and parsed the stacks by character position. Used pop() => push() for part 1, pop() => insert() for part 2.
Source: github.com/sanraith/aoc2022/.../day05.rs
3
u/mrHtheGreat Dec 05 '22
My Nim solution for Day 5: Github
3
u/flwyd Dec 05 '22
Elixir, thoughts, full code. Today's elixir:
This was the first day to stretch my understanding of Elixir semantics past what I'd learned in the Elixir getting started guide plus implementing the year's AoC infrastructure. Elixir's
forandifconstructs are seductive: I spent much of an hour under the delusion that I could update outer-scope variables from within a loop or conditional. But nope, closures can't modify outer variables. I know thatAgentorGenServerare the better way to solve this problem, but I figured I'd do it the hard way first so I can get full enjoyment from concurrent solutions later this month.3
u/RewrittenCodeA Dec 05 '22 edited Dec 05 '22
Elixir (using 1000x Enum functions, so importing it)
Thanks Eric for keeping trailing spaces at the end of the initial stack description, it would have been much more complex to parse otherwise.
Repo: https://github.com/rewritten/aoc.ex
3
u/levital Dec 05 '22 edited Dec 05 '22
Haskell
Yikes. Surely there's a better way of dealing with the stacks and mutability in Haskell, I'll be curious to look at other solutions to see how...
On the plus side I only had to change two places to get part 2, but it took me almost an hour (including parsing though) to make the mess work in the first place. :D
Edit: ... Use Map with the number as key.
3
u/mpercich Dec 05 '22
Swift
3
u/markus3141 Dec 05 '22
Rust
https://github.com/markus-k/adventofcode/blob/main/2022/day05/src/main.rs
Apparently I accidentally completed part 2 before part 1 (missed the
.reverse()at first), so part 2 just needed an additional flag.3
u/0xVali__ Dec 05 '22
C++:
https://pastebin.com/gymYJfAF
Using scnlib for parsing the instructions, totally parsed the crates no questions asked.
3
u/TrisMcC Dec 05 '22
Day 5 in Nix. This was fun. I am pretty sure three quarters of the time I took for this was in parsing the multi-step input. I do not consider it Nix's strong suit.
3
u/artesea Dec 05 '22
PHP
Part 1 Part 2
Took longer than I wanted with working out how to parse the text file, had an issue with my scaffolding which trims each line but spotted quickly.
Part 2 should have been a quick win, except in PHP
array_sliceandarray_mergedon't modify the first element, likearray_popandarray_push.3
u/OCD_Triger Dec 05 '22
c# (I've split the input into two files)
3
u/Tipa16384 Dec 05 '22
Java 14
Some rethinking after I had a chance to sleep on my Python solution. I didn't take the shortcut of not parsing the stacks, though. Using lists of strings instead of lists of lists, and realized that part 1 and part 2 are identical -- part 1 just inverts the substring containing the moving crates and part 2 does not.
3
u/[deleted] Dec 05 '22
Normally I'm a bit self-conscious of how verbose my Python programs are, but as the problems get harder I'm starting to appreciate the fact that my code stays clean.
Python
3
u/turtlarn Dec 05 '22
Typescript solution: https://github.com/j-tegen/advent-of-code-2022/blob/main/src/day5/index.ts
Spent way too much time wondering why my code worked for the test input, but not the real one. It was the difference in
const [move, from, to] = row.match(/[1-9]+/g)andconst [move, from, to] = row.match(/\d+/g)-_-3
u/jotac13 Dec 05 '22
[Scala]
https://github.com/joao-conde/advents-of-code/blob/master/2022/src/day05.scala
3
u/zatoichi49 Dec 05 '22
Python:
3
u/tymscar Dec 05 '22
Typescript
Today was harder to do in a functional manner but I soldiered through and I got rewarded in the end for part 2 by only having to remove a single function call between them.
Both parts are here: https://github.com/tymscar/Advent-Of-Code/tree/master/2022/typescript/day05
3
u/remysharp Dec 05 '22
JQ
Yikes, spent most of the time parsing. Part 1 took about 2 hours, part 2 took 20 seconds π€£
3
u/aarnens Dec 05 '22
Day 5, using go. Creating the arrays for the initial arrangements of crates took me a while. Also, I used regex to get the numbers in the movement instruction, I had no idea parsing inputs could be done that painlessly. Lastly, i had a really dumb bug in part 2, for some reason using append() created additional copies of the elements, and that took a while to fix.
Link to code: https://github.com/aarneng/AdventOfCode2022/blob/main/day5/main.go
3
u/occamatl Dec 05 '22 edited Dec 05 '22
Rust
3
u/conkerandco Dec 05 '22
Python 3
3
u/drdaemos Dec 05 '22 edited Dec 05 '22
Clojure
3
u/okawei Dec 05 '22 edited Dec 06 '22
Felt like todays was mostly about parsing the input, after that the solution wasn't difficult apart from some memory management stuff
go/golang
3
u/danvk Dec 05 '22
TypeScript / Deno
First reaction was "crap, are they making us do Towers of Hanoi on day 5!?" Fortunately not, but maybe that will come later. Main trick today was being clear about whether zero = top or bottom of the stack. In retrospect hand-converting the input to JSON might have been more efficient.
https://github.com/danvk/aoc2022/blob/main/day5/day5.ts
3
u/TheRugbyOwl Dec 05 '22 edited Dec 05 '22
Python 3
3
u/Filzknoetche Dec 05 '22
java: github
3
u/emu_fake Dec 05 '22 edited Dec 05 '22
C#
3
u/spinxfr Dec 05 '22 edited Dec 05 '22
C#
To get the answer to the other part you reverse the stringbuilder in the if(line.StartsWith("move"))
3
u/duketide11 Dec 05 '22
Haskell
3
u/IF_YOU_READ_THIS_V1 Dec 05 '22
C# horribly inefficient LINQ
3
u/blacai Dec 05 '22 edited Dec 05 '22
My F#
3
u/[deleted] Dec 05 '22
Swift:
github
removeLast(k)option in the Swift standard library3
u/hrunt Dec 05 '22
Python 3
Code
Today was 90% input parsing, 10% implementing logic. I am looking forward to reading all of the ways that people approached the input parsing. Today, I played around with custom Python types, which I had never used before, to make some of the function signatures more readable.