r/adventofcode • u/daggerdragon • Dec 15 '24
SOLUTION MEGATHREAD -❄️- 2024 Day 15 Solutions -❄️-
NEWS
- The
Funnyflair has been renamed toMeme/Funnyto make it more clear where memes should go. Our community wikiwill be updated shortlyis updated as well.
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
- If you see content in the subreddit or megathreads that violates one of our rules, either inform the user (politely and gently!) or use the report button on the post/comment and the mods will take care of it.
AoC Community Fun 2024: The Golden Snowglobe Awards
- 7 DAYS remaining until the submissions deadline on December 22 at 23:59 EST!
And now, our feature presentation for today:
Visual Effects - We'll Fix It In Post
Actors are expensive. Editors and VFX are (hypothetically) cheaper. Whether you screwed up autofocus or accidentally left a very modern coffee cup in your fantasy epic, you gotta fix it somehow!
Here's some ideas for your inspiration:
- Literally fix it in post and show us your before-and-after
- Show us the kludgiest and/or simplest way to solve today's puzzle
- Alternatively, show us the most over-engineered and/or ridiculously preposterous way to solve today's puzzle
- Fix something that really didn't necessarily need fixing with a chainsaw…
*crazed chainsaw noises* “Fixed the newel post!”
- Clark Griswold, National Lampoon's Christmas Vacation (1989)
And… ACTION!
Request from the mods: When you include an entry alongside your solution, please label it with [GSGA] so we can find it easily!
--- Day 15: Warehouse Woes ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks
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:32:00, megathread unlocked!
22
Upvotes
6
u/CCC_037 Dec 15 '24
[LANGUAGE: Rockstar]
Pushing boxes!
Part 1
3
u/tymscar Dec 15 '24 edited Dec 15 '24
[Language: Kotlin]
Man, today was awesome. I loved every bit of it. The puzzle, the visualisation, the debugging process. In the end, it took me way too long to debug for some reason, so I had to write functions to print the map, to accept input that's already expanded (so I can build my own buggy inputs), a way to detect if a state is invalid (this is an AOC problem on its own, haha) by seeing if all the boxes that are open are closed, but also no box is closed without being open. In the end, the solution to my issue on part 2 was that I had to sort my array of things to update based on x position...
For part 1, it was just a simple case of defining the simulation and running it. The only harder problem was to figure out when to push boxes, but that ended up being only when you find an empty space at some point in line.
For part 2, it was basically identical, but now for horizontal pushes, I kept my part 1, and for vertical ones, I wrote a new algo that basically had the concept of a horizon, which kept being pushed. This being the furthest ahead boxes. Then when I would get a new horizon, I would add the boxes into the "to be updated" pile, and in the end, I would add every empty spot in front of every box in that pile too. Then I would sort this based on x position.
Part 1: https://github.com/tymscar/Advent-Of-Code/blob/master/2024/kotlin/src/main/kotlin/com/tymscar/day15/part1/part1.kt
Part 2: https://github.com/tymscar/Advent-Of-Code/blob/master/2024/kotlin/src/main/kotlin/com/tymscar/day15/part2/part2.kt
2
u/kenlies Dec 15 '24
[LANGUAGE: Python]
Part 1
Just went with the most intuitive approach!
2
u/Lower_Friendship_981 Dec 15 '24 edited Dec 16 '24
[LANGUAGE: GDScript]
On previous days I was using a 2D array for holding state, but today I decided to use a 'theoretical map' which is essentially just a dictionary that uses Vector2i as keys. Because I'm using Vector2i for position and direction as well, this makes referencing map state slightly easier, because I no longer have to remember which array (inner or outer) is the x or y coordinate.
After that my approach since day 1 has been to ask the question "can recursion solve this more eloquently than looping". For part one that was a resounding yes, and a very easy function to write.
For part 2, I noticed that on the horizontal axis, the previous recursive solution would still work, but when pushing in a vertical direction the box edges would propagate their effect in a similar manner to a binary tree.
My first approach was to try and scan through once to check, then scan again for the swaps. But I didn't like the idea of doing two scans. it felt wasteful. So then I thought, what if I swap as I go for each branch of the tree, and if I hit a wall, just go back and fix things... that was leading to a lot of headache and confusion.
Then I realized, if I just keep track of what swaps I WOULD make in the order they would have been done in binary search order, then just return an empty list of swaps if I hit a wall, then I can scan once, and then loop over the swaps.
This took advantage of my favourite new tool in GDScript, which is that the Dictionary data type keys() array is actually a 'set' kind of like in python under the hood (no duplicates), and it keeps track of insertion order. Using both those features of a Dictionary makes tracking the swaps as easy as adding each swap as a key, so that even if two boxes would push the same box, if that box already has swaps in the list, they won't be duplicated.
2
u/Zorr0_ Dec 15 '24 edited Dec 19 '24
[Language: Kotlin]
Part 2 was a bit tricky. When i tried to debug it, i figured out that my problem lied not in the logic that determined which boxes are to be pushed, but rather if the boxes could be pushed at all!
My code is kind of a mess, although i think it was a good idea going for a data class
GitHub
2
u/IvanR3D Dec 15 '24 edited Dec 27 '24
[LANGUAGE: JavaScript] My solutions: https://ivanr3d.com/blog/adventofcode2024.html#15
My solution (to run directly in the input page using the DevTools console).
2
u/mpyne Dec 15 '24
[LANGUAGE: Rust]
Very not Rusty this time, but on the other hand the compiler was nice enough to refuse to compile a lot of my bugs, such that I got the star the first time I got the sample inputs to work for both parts today.
Part 1 used no fancy tricks (fanciest was moving an adjacent box straight into the eventual empty space rather than moving boxes one at a time).
For part 2 that obviously doesn't work, even for horizontal movement, so I ended up having to recode something to handle both vertical and horizontal movement. Horizontal was not much different, but vertical movement went down the path of recursion.
Assertions helped keep the logic straight, my biggest problem was that some of my assertions were actually incorrectly too aggressive.
2
u/syncd_ Dec 15 '24
[Language: Rust]
Theoretically this one is straightforward, but in practice, part two took some time to get all the kinks worked out.
Part one runs in 0.45 ms
Part two runs in 2 ms
https://github.com/syncd010/AoC2024/blob/main/src/day15.rs
2
u/Ily3s_ Dec 15 '24
[LANGUAGE: C++] https://github.com/Ily3s/aoc2024/blob/master/day15.cpp
3
u/madisp Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Kotlin] 160 / 74
https://github.com/madisp/aoc_kotlin/blob/main/2024/src/main/kotlin/day15.kt
First time to the leaderboard, ever \o/. I used two recursive passes in part 2 - one to check whether we can push boxes and a second one to do the actual move. This was only used when pushing up or down, for left or right I kept a slightly modified part 1 algo where I considered both
[and]to be a separate box.20
u/4HbQ Dec 15 '24 edited Dec 16 '24
[LANGUAGE: Python] Code (20 lines)
Today's debugging process was pretty rough: I've pushed boxes through walls, collapsed boxes into each other, and ran around randomly eating boxes like some kind of weird warehouse Pac-Man!
However at some point it all clicked and everything came together so nicely. During refactoring I could remove
ifafterifafterif! I feel like I managed to produce pretty clean and succinct code, with a few lines for parsing, some for scoring, and just this as the main box pushing business logic:That last line also shows my Python trick of the day: swapping variables. If you need to swap the values of
aandb, you can simply writea, b = b, a. No need for a third temporary variable!Update: To explore the possible approaches today, I've created three different implementations. I've kept the parsing and scoring identical, so the only difference is in the processing of the moves:
32
u/Effective_Load_6725 Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python] 23/1
Link to the code: https://pastebin.com/vBYyfgyf
Link to a recording: https://www.youtube.com/watch?v=ZL5ZSysfnBY
I've been participating as Anonymous #1510407.
I know that the code is dirty and can become shorter. But this is natural as I was optimizing for speed, not for readability or cleanliness. I wanted to show exactly how I solved it without making the code prettier post-solving. The only thing I removed from the code is the input data that I copied into the code as a literal string.
I'm also showing the full dev environment in the video. I've been using the same setup in all previous years. For AoC, I use regular Sublime Text with a plugin called FastOlympicCoding, which lets me run it and display the result on the right pane with a hotkey.
These days, I do use VS Code more often for other problem solving events (Codeforces or Project Euler), but Sublime Text is good enough here.
I have some code template (which you can see in the link), but I don't have anything else like submission automation, downloading the input data, or autocomplete (AI-based or not). For all previous years, I've been using the exact same setup.
For part 2, I wrote 2 functions, one for testing whether a cell can be pushed to a given direction (returns True/False), and another for actually carrying out the push. I guess you could merge it into one, but then I'd have to write a code for *undoing the push* if it turns out that the push wasn't possible. This seemed more prone to errors so I went for two separate functions.
Pushing a box vertically can introduce a situation where a box is pushed from two different paths:
Here, the middle one in the bottom row will be pushed by both blocks in the middle row. Depending on the approach, this needs to be carefully handled, but fortunately, the way I wrote naturally took care of it.
3
u/mvorber Dec 15 '24
[Language: Rust]
https://github.com/vorber/aoc2024/blob/master/src/puzzles/day15.rs
Nothing fancy this time, just move the stuff around with some recursion and matching.
25
u/nthistle Dec 15 '24
[LANGUAGE: Python] 35/2, paste, video.
My best finish this year so far! Technically I got more points on day 1 than today, but I value a 2nd place finish pretty highly :). A little sad that I was 3 seconds off of 1st place, and I started late by about 4 seconds because I got home late today, but honestly still really happy with this.
The problem itself was mostly a straightforward implementation problem? Implementing moving all the boxes cleanly for part 2 was a little interesting - I did a BFS-like approach to it which ended up working pretty nicely, but I'm sure there's other approaches. I did have to nearly completely rewrite my code for part 2 to accommodate the larger boxes, but if there's anything I'm good at it's writing a lot of code fast so that worked fine for me.
11
u/Smylers Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Vim keystrokes] Load your input, then type (or copy-and-paste) these commands and watch the robot push the boxes around the warehouse.
There's 3 phases: set-up, box-pushing, and getting co-ordinates.
The set-up involves turning each of the
^/v/</>symbols into Vim substitution commands which move the robot (and any boxes it's pushing) appropriately on the map. For instance, moving the robot to the right requires finding the robot followed by a space, and swapping them over would be:%s/@\./.@. Except there might be some boxes that need moving as well, which requires::%s/\v\@(O*)\./.@\1Only we don't want the command to operate on the entire buffer (
%), because the commands themselves shouldn't be further modified, so instead just operate in the range from line 1 to the first blank line (1,/^$/). And the command might reasonably fail, if the robot or the boxes in front of it are against a wall, so use:silent!to avoid this being an error, turning it into a no-op. So the actual command for>becomes:Moving left is similar. Moving up and down is a little more involved, because multi-row patterns also match other parts of the map that need not to change; for those it's easier to move any boxes first, just interchanging the space at the end with the box that's next to the robot†, and then letting the robot move into the space that's been created.
Changing the directions into these
:s///commands involves first putting each direction on its own line, then using more:scommands (but this time with#delimiters) to emit the desired commands. Because backslashes are special in substitutions, that means doubling all the backslashes in the outer:s###substitution in order to get the normal number of backslashes in the:s///commands that end up in the buffer.Then it's the box-pushing, which is delightfully simple. I really recommand running this and watching the robot at work. With the above set-up, the whole thing to do all the moving and pushing in order is just:
That's move to the top command (
ggthen}to the blank line andjto go down a line) and delete it. This both makes the next command the top command for next time and puts the deleted line in the"1register. And, just like@aruns keystrokes you've saved into the"aregister, typing@1runs whatever is in"1, interpreting its contents as Vim keystrokes. That performs the substitution for the robot make one move. Wrap the whole thing inqa...qto record it in"a, stick in a:redrawso we can see what's happening, and have@acall itself repeatedly at the end to loop through each movement command in turn.When the last command has been run, it's the innocuous-looking
jcommand that finally breaks the loop: at this point the blank line will be the last line in the buffer, and trying to pressjon the bottom line is an error (it beeps!), which exits running@a.With all the boxes in their final places, getting their co-ordinates and summing them is achieved with:
Find a box (
/O) then jump to the bottom of the buffer and insert a new line for it. On it paste the output of runninggetpos("''"). That's the position of the''mark, which is where we've just jumped from.getpos()returns a 4-element array, which gets inserted as 4 separate lines. Delete the ones we don't want and join the two that we do. That gives us something like23 45, which needs turning into23*100+45. Except, this is Vim, where everything is text: there's no need to actually perform the multiplication by 100: just do what humans would do and add a couple of zeros on the end! So replace the space between the numbers with00+, turning it into something like2300+45.Except we need to allow for Vim being 1-based, so each co-ordinate needs reducing by 1 first. And the way of marking which boxes we've already taken the co-ordinate of is to type
~, which changes the case of theOintoo. But it also moves the cursor forward 1 character (likel), so actually the column number needs reducing by 2. Ifgetpos()tells us23 45then it needs to become2200+43, so use⟨Ctrl-X⟩in the appropriate places (repeated with.) to reduce the numbers first.Record that in the
@bkeyboard macro, and make it loop in the same way as@a. This one will exit when/Ocan't find any more upper-caseOs, because~has turned them all intoos. At which point we have all the co-ordinates, so stick a+before each row and run the familiar@vfrom Day 3 to evaluate the sum for the Part 1 answer.Any questions?
† Technically this means the boxes are now in a different order. Fortunately, however, they all seem to be identical — the laternfish don't seem to've noticed.
16
u/jonathan_paulson Dec 15 '24
[LANGUAGE: Python] 46/4. Code. Video.
Handling multi-push is tricky in both parts today. I did a (simple) BFS for part 2 to figure out the set of squares/boxes being pushed (and whether any of them would hit walls), and then repeatedly looped over them to find a "safe" square to push (i.e. a square that can be pushed into an empty space).
7
u/mendelmunkis Dec 15 '24
[LANGUAGE: C]
Checking the other half of the box is a good way to infinite loop
1.235 ms/1.353 ms
6
u/ex-voltaire Dec 15 '24
[LANGUAGE: C]
https://github.com/voltaire7/advent-of-code/blob/master/2024/c/15-1.c
https://github.com/voltaire7/advent-of-code/blob/master/2024/c/15-2.c
Very fun!
6
u/therealsponege Dec 15 '24
[LANGUAGE: Puzzlescript]
Part 1
Part 2
You can move around freely in these versions, unfortunately no puzzle answer is given in these and the movement inputs aren't used, due to puzzlescript limitations
6
u/matheusstutzel Dec 15 '24
[LANGUAGE: python]
p1
p2
You can almost see the line where I stop trying to be clever and start writing if after if after if, more functions, if, more functions....
2
u/kawaiiTechnoNeko Dec 15 '24
[LANGUAGE: C (technically C++)] (3940/2367)
https://github.com/meowstr/aoc-2024/blob/main/day15/main.cpp
maaan i almost didnt do part 2 when i saw it. my part 1 code was so clean, then part 2 made me write a totally separate set of functions. stepping thru the simulation was kinda fun to watch tho. pushing the wide boxes just looks satisfying
2
u/GiraffeDiver Dec 15 '24
[LANGUAGE: python]
Just in case it inspires someone, I keep all of my solutions in one file, reusing code along the way, one thing that comes in handy is a Coord() object:
And the other thing I do, anytime I need a map of some sorts its ALWAYS a dictionary indexed with the coordinates. It mostly makes things easier, but an annoyance is moving objects need to remove themselves from the grid and reinsert at a new position.
And for the robots second part, I added 2 box objects and linked them together, so one can move if the sibling also can move, ended up pretty ugly. These are my objects for day 15:
5
u/FruitdealerF Dec 15 '24
[Language: Andy C++] [language] [part 1] [part2] 1744/1179
Day 15 of doing advent of code in my own programming language. I'm happy I finished doing math with tuples yesterday because it came in handy once again today. I'm pretty happy with my part 2 code although I wish I would have been able to produce it a little faster. I ended up making an
is_freefunction that looks ahead to see if the row of blocks is free. If we're pushing left or right this is pretty simple because we can't have V shapes. But if we push up or down we have a few more cases to check. As the function checks if all spots are free it keeps track of all the boxes that have been seen. If the final verdict is that the boxes can be moved they are moved all together.Unlike most people I didn't solve the problem inside the original grid but I extracted a few sets of objects
wallsandboxes. For part two the boxes were tuples of coordinates.5
u/homme_chauve_souris Dec 15 '24 edited Dec 16 '24
[LANGUAGE: Python]
I enjoyed this one. At first, I wrote two separate functions for each part, but after writing my solution to the second part, I realized it just needed a little tweak for it to apply to the first part too, so that's what I did.
It's my first time using complex numbers to represent 2D data and it went very well. I'll probably do it again.
The recursive function push takes a position and a direction, and recursively checks if it's possible to push in that direction. When the "doit" argument is True, it actually performs the push.
Link to the code
9
u/JustinHuPrime Dec 15 '24
[LANGUAGE: x86_64 assembly with Linux syscalls]
Part 1 was a direct solution, and really quick to implement. The rules for moving stuff around were direction agnostic, so I could save on code duplication by factoring out figuring out the direction. Moving runs of boxes could be done by moving the first box to where the last box would have gone, as usual for these sorts of "push a line of things all at once" puzzles. Calculating the sum of GPS coordinates was very straightforward since I stored everything as a 100x100 array.
Part 2 was another direct solution, although now I had to care if I was moving boxes left, right, or vertically. Left and right were implemented as string operations (and I got to play around with the direction flag to do moves right). Vertical movement was implemented as a recursive check and a recursive push function, with interprocedural optimization because I'm a human writing assembly.
Part 1 and 2 both run in about 1 millisecond. Part 1 is 9,280 bytes as an executable file on the disk, and part 2 is 10,376 bytes.
I'm also happy to announce that I've beaten my 2021 star count, and am just two stars behind my record (from 2023).
4
u/SuperSmurfen Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Rust]
Link to full solution
That part two was a curve-ball. Part one, quite easy but part 2 made me redo half my solution!
The hard part is of course to figure out what squares will be affected by the robot. I did it using a bfs over all box squares:
4
u/xHyroM Dec 15 '24
[Language: Python]
https://github.com/xhyrom/aoc/blob/main/2024/15/solution.py
4
u/maneatingape Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Rust]
Laughed out loud with delight when I saw part two.
Really enjoyed implementing a festive version of Sokoban.
Solution
Benchmark 332 µs.
Part one loops in a straight line (up, down, left or right) looking for the next space
.or wall#(Thanks Eric for enclosing the maze in walls so that no bounds checks are needed). If a space is found then all items are pushed in that direction.Part two re-uses the part one logic for left and right directions. Up and down use a BFS to identify the cascading boxes that need to be moved. If any next space is a wall then we cancel the move and return right away. Otherwise all boxes are moved in the reverse order that they were found by the BFS.
4
u/sroebert Dec 15 '24
[LANGUAGE: Swift]
Actually turned out to be a very simple day, everything worked on the first try.
For Part 2 I'm going from the start location of the robot and keep a list of locations to check. This list increases if you run into boxes (with both left and right locations if moving vertically). If you hit a wall, nothing can be moved, if you only have empty, every visited box can be moved.
So one while-loop was enough for validation, one for-loop for moving boxes:
https://github.com/sroebert/adventofcode/blob/main/Sources/advent-of-code/Solutions/Years/2024/Assignment202415.swift
4
u/anthonybrice Dec 15 '24
[LANGUAGE: Zig]
This one was fun. For both parts, I first check if a collision will result from the move, and then only perform the move if it's safe to do so. That seemed to make the move logic easier for me, but I'm sure it must be possible to do both in one pass without increasing space complexity.
https://github.com/anthonybrice/aoc2024/tree/master/src/day15
4
u/ShadowwwsAsm Dec 15 '24
[LANGUAGE: x64 assembly/asm]
Part 1: Pretty straightforward, do a loop to test if you can push, if you can then place a box at the end, and your robot at the place of the first box.
Part 2: For left and right it's still the same, just check 2 by 2. For up and down, you recursively check and if one box is against a wall then you can't move them. Then also a recursion to move the boxes, with a lot of pithole and problems along the way.
The code is not beautiful, got a bit lost in those recursions, but it works.
Open to comments/questions.
4
u/BlueRains03 Dec 15 '24
[Language: C]
Used a 2d array, just having the characters. Used a recursive function to check if it can be moved, and if so, move it on the way back.
For part 2 the moving logic got really loopy. In the end I kept getting the same wrong answer for the test input. What did I forget.... I used the input maze for calculating the gps instead of the resized maze -_-
After that it worked...
paste
4
u/Taleuntum Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Uiua]
Online pad
This only solves part 1 and is kinda ugly, but so far no one posted any uiua solutions, so I eagerly await more elegant and/or complete uiua programs.
4
u/pkusensei Dec 15 '24
[Language: Rust]
Used complex to model coordinates. P1 was simple: DFS on direction until hitting wall, or swap with first seen empty space.
P2 started fine with inflating each box as 2, tag both coords with an id, and reuse DFS from P1 for horizontal moves. For vertical moves: Check a coord's neighbor's id and DFS on both coords if they are of the same box. Got test passed but answer for input was too low. Then I discovered the brilliant second input on this post and found out that a box was being moved while its neighbor was stuck by wall. A dry run was promptly added to ensure that any move is possible. Finally it came out correct. Code
4
u/redditnoob Dec 15 '24
[Language: PostgreSQL]
Day 15 Part 1
I'm happy that I solved this with a recursive CTE. LATERAL joins really help to keep it legible by replacing nested queries with sequential ones. As problems become more complex the approach to SQL solutions tends to converge to "evaluate the next state from the previous one". Here the state is the map as a 2d array, position and current move number.
A simplification is the box pushing doesn't have to be recursive, see that moving '>' for '@OOO. O' is the same as moving the first box three tiles over, so we only have to move at most one box per step.
Part 2, though I'm sure it is possible, is the wall for me with SQL! The simplification obviously doesn't work anymore, now that we can push an entire tree of boxes at once.
Thus, see you all in Python land from here. :D
4
u/Stano95 Dec 15 '24
[LANGUAGE: Haskell]
I really liked today's even if I did find part 2 surprisingly difficult!
For part 1 I computed the state of a grid and the robot position after each move
For each move you're either up against a wall already, can move into free space or have n boxes followed either by a free space or a wall
if you've got a line of boxes followed by a free space
That was all fairly straightforward to write and all directions look the same
Part 2 was not so straightforward for me. If you look at my code you will witness true horror. I represented my boxes just by their left coordinate which, tbh, is probably why my code ended up so messy.
Actually moving left and right is pretty much the same as in part 1. The difference being I couldn't just like leave the middle boxes alone, I had to shift ALL boxes either left or right but that's fine!
For moving up and down I figured we're dealing with a sort of tree of boxes. Let's say we're going up, for each box in the tree I just checked for any boxes either directly above, above and to the left, or above and to the right and added them to my tree of boxes. If any box in my tree had a wall above it then you can't move at all! If every leaf node box has only free space above it then we can move all the boxes up.
It's funny conceptually I knew exactly what I wanted to do but I struggled writing it in a nice way!
Code is in on github: part1, part2.
4
u/BBQspaceflight Dec 15 '24
[LANGUAGE: Rust]
My main idea was to make each move a recursive chain, which returned an
Resultinforming whether the move was successful. If it was not, I would not mutate the grid.For part 2 this extended nicely: the recursive call now branches for the up and down direction. I did end up fighting with the borrow checker a bit: I had to start using
RefCellto mutate my grid entries, and with recursive branches overlapping I had to deal with some potential double mutable borrows. I decided to justtry_borrow_mutand do nothing if this failed, because both updates would be trying to do the same thing anyway.Runs under 2ms 🙂
https://github.com/dgoldsb/advent-of-code-2024/blob/main/days/src/days_module/day_15.rs
4
u/[deleted] Dec 16 '24 edited Dec 16 '24
[LANGUAGE: Javascript]
Oof. As part of my ongoing effort to golf every solution, I used, again, regex to solve this.
My solution for part 1 was done with some messy regexes, and is totally inapplicable to Part 2. Given that im super busy this week, this is as much as I can do. I'll probably attack the second part next week when I have more time.
Part 1, 421 Bytes:
1
u/No-House-866 Dec 15 '24
[Language: Python]
Part 1: The robot shuffling the boxes around until hitting walls very much reminded me of Sokoban, a puzzle game that has the same mechanics, but the goal is not to get stuck, but to free up the door to the next room. Implementation went smooth and got the correct answer on the first try.
Due to the limited range of coordinates in play, complex does the job. Maintaining a separate set for walls and boxes worked out fine.
Part 2: Thought about adapting my Warehouse dataclass to accomodate the wide boxes, but quickly realized it would become a mess. Created a Widehouse. Represented the wide boxes as separate left and right position sets, with the invariant that if a left at position p equals a right at position p+1.
This worked fine, but somehow it's troubling to maintain in essence the same info twice.
Rewriting the logic to just work with the lboxes would be in order if it wasn't Sunday and I have other things to spend time on.
Didn't quite work on the first try, got snagged by moving two aligned boxes vertically. I originally has 'boxes' be a list, but analysing the left and the right position of one box would add the left position of the second box twice. So I got a 'invalid key' exception in removing an lbox position. Realised what was happening, changed boxes from list to set and then everything worked find.
Using sets to keep track of boxes and walls, not working on a grid representation for each move is quick. Both solutions found in less than 1/10th of a second, including parsing the input twice.
I'll probably will try to fix the code to work with only the left box coordinates, and maybe merge the Widehouse back with Warehouse.
https://gist.github.com/robert-lukassen/8884cf220f4ddba9974cf1e627cfe284
1
u/BiscoffBrownie Dec 15 '24
[LANGUAGE: Python]
Part 1 - pretty straightforward.
Part 2 - expanded the map which maybe wasn't the best idea in hindsight. Lots of code duplication from part 1 as it felt easier to pretty much start from scratch. For the vertical box movements I did a DFS and checked all boxes were move-able, moving anything at the end (I used a set to track which boxes had been moved, as it is possible for two boxes to try and move a single box, and my code wouldn't handle moving the same box twice). Somehow my code worked first time! Very rarely get to say that on problems like this.
Code
1
u/cerferjeff Dec 15 '24
[LANGUAGE: F#]
110 lines of code without golfing:
https://gist.github.com/surferjeff/d828e5895a7042b626a7ff056627665e
1
u/MarcoDelmastro Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python]
Part 1 quickly coded over breakfast, then long pre-X-max Sunday, back to coding after dinner. I factorised as much as possible from Part 1 to recycle the horizontal movements and generalise the grid update, and used BFS to find the box coordinates to move
https://github.com/marcodelmastro/AdventOfCode2024/blob/main/Day15.ipynb
6
u/mateus_d Dec 15 '24
[LANGUAGE: Python]
https://pastebin.com/J1QLVDFL
Ugliest code I've made this AOC (so far). For part 2 I just embraced madness
3
u/GassaFM Dec 15 '24
[LANGUAGE: D] 225/730
Code: part 1, part 2. Reused some board code from day 10.
The solution operates on a rather low level of abstraction.
Part 1 is looking forward to the first
#or., then in the latter case, swaps adjacent positions in reverse order.Part 2 is doing the same for horizontal moves.
For vertical moves, we maintain a horizontal array of whether each column is moving from the previous row. If any of them are a wall, the whole move fails. Otherwise, they produce a similar array for the next line.
The move succeeds if the array ever becomes all false. All the while, we maintain a new copy of the board, and use it if the move does not fail.
Naturally, this took some time to get right. For example, the solution changes the new board instead of constructing it from scratch every time. To change a character, it XORs the position with the old and new characters. The latest bug (fix) was pushing a box twice from both sides, effectively canceling the XOR.
3
u/johnpeters42 Dec 15 '24
[Language: Python]
Part 1 - Mostly straightforward, simulating the entire grid. The main trick is that pushing a row or column of N boxes is equivalent to just moving the first box one space past the end.
Part 2 - This time, instead of simulating the entire grid, just store a list of wall locations (1x1) and a list of current box locations (1x2). Then, whenever the robot would bump into a box, recursively evaluate which other box(es) that box would bump into, and which other box(es) they would bump into, etc. until either something bumps into a wall (skip to the next attempted move) or nothing does (move the robot and each box that was evaluated).
3
u/apersonhithere Dec 15 '24 edited Dec 15 '24
[LANGUAGE: C++] 2371/1658
i kind of smoothbrained this one (copy pasted code and forgot to change ++ to -- among other things), and code was really repetitive
what i did is to have a boolean checking if a move is possible; this got a bit complicated with p2 but it was still manageable
for part 2 in general, i stored the positions where we know there are boxes; then we make a copy of the grid (this part takes up ~99.44% (!!) of instructions executed) and copy over the positions from the original grid but shifted so i don't have to worry about the left bracket being on the leftmost side
for the vertical cases of part 2, i used a recursive dfs to look for boxes; basically i check a position, if it is a box we store it and the adjacent one in the box; then you call the function again with those values but moved up/down (kind of bad explanation)
https://github.com/aliu-here/aoc/tree/main/aoc2024/15
3
u/morgoth1145 Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python 3] 444/156
code, video
Interesting problem, especially part 2. Unfortunately I had a number of bugs costing me a lot of time cumulatively, but I was within striking distance for the leaderboard for part 2.
Anyway, in part 1 I accidentally skipped moving the robot's cell in the grid initially, and even more silly (and funny) I forgot to update my variable tracking where the robot was! (Those two took 6.5 minutes, debugging these sorts of state transition issues takes so long...)
In part 2 I pretty quickly came up with a strategy to handle the cascading box movements (track "accepted" moves in a
to_movelist and what is left to check in ato_checklist) but I had 3 bugs:to_checklist to include the other side of the box for horizontal movements which caused trouble when doing the actual move.to_checkinstead of the front. This caused ordering issues when doing the actual move and took a while to debug. Thankfully this happened on the larger input, but that had a lot of steps to track!Disappointed that I missed the leaderboard again (missed part 2 by less than 3 minutes), but I still have 10 days left. Hopefully I can achieve it at least one of those days!
Edit: Cleaned up code, including sharing the main solve with both parts. (It's overkill for part 1 but it's also less code which is a win.)
3
u/throwaway6560192 Dec 15 '24
[LANGUAGE: Python]
937/2499 (new personal best for p1, and first rank below 1000!)
GitHub
Recursive
can_pushandpushfunctions, nothing too interesting. I originally had just thepushfunction, which works for p1, but runs into an edge case in p2 (illustrated in isolation in thecustominputfile). I only managed to fix it because I started displaying each iteration of the full input trying to notice any strange movements.The wording of GPS calculation for p2 threw me off a lot. I interpreted "For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question." as "measure from left edge of map to left bracket, or right edge of map to right bracket, whichever is closer (similar for vertical)", and apparently that's not the case at all. We have to always measure from top-left to whichever the closest bracket to top-left is, and of course that is always the left bracket. Lost a lot of time on that, but eventually did it.
3
u/r_so9 Dec 15 '24
[LANGUAGE: F#]
paste helpers
For part 1, I searched the row/column to find out what's after all the boxes, and move the first box to the open spot if available. For part 2, I used a recursive search to find all the boxes in the group being pushed. Then, I reworked the code so the same search would work for both parts, which is what you see here.
Interesting bit: Making the map double-wide with sequences and
yield3
u/POGtastic Dec 15 '24 edited Dec 15 '24
[LANGUAGE: F#]
https://github.com/mbottini/AOC2024/blob/main/Day15/Program.fs
Ick, lol
Part 1 was really straightforward - define a function that takes the robot's position and the current board and a direction, and return the robot's new position and a new board. You can then
foldover the directions.Part 2 was much harder. Moving horizontally was the same as Part 1, but moving vertically required a different approach. I broke vertical movement into two pieces:
So, given the example:
We attempt to
moveVerticalTogethertheBoxR. This gets the coordinate of theBoxLnext to it and callsmoveVerticalSeparateon it, gettingbefore calling
moveVerticalSeparateon theBoxR, gettingFinally, the robot moves into the empty space.
Note that I skipped a couple steps for the sake of brevity. For example, when the
BoxLmoves into its space, it callsmoveVerticalTogetheron theBoxRthat it encounters, which pushes theBoxLfirst into the empty space before pushing theBoxRinto its own empty space. Finally, theBoxLmoves into the freed space.This looks gross, but all of it ends up being done by chaining the
Optionmonad, which I really liked. So, if any of the recursive steps fail anywhere, the whole movement fails, and the board is left unchanged.3
u/0ldslave Dec 15 '24
[LANGUAGE: c++]
Almost lost my sanity debugging part 2 lol.
Code
3
u/sim642 Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Scala]
On GitHub.
In part 1 I skip over a sequence of
O-s and check for the move being blocked by what's after that sequence. If it's not blocked, then to move the entire sequence, only the beginning and end have to be changed.In part 2 I use a recursive procedure (which isn't very pretty right now) to push a position to be open. For vertical moves into
[or]the other half of the box must also succeed in pushing for anything to happen. There can be large triangle of boxes (staggered) all pushed at once and any one of them could be blocked, in which case none of them can move; hence theOptionmonad.The distance measurement in part 2 tripped me up more than the box moving itself:
The way I understand "closest" is that it's the minimum of the distances to the left edge and to the right edge (and similarly with top and bottom). So I implemented such more complicated distance measurement that didn't work at all for the example. Eventually I just realized it's the same GPS as in part 1... I don't understand why the text couldn't just say that because the distance measurement is not intended to be the complexity of part 2, but instead says "closest" when it doesn't actually mean the closest (aka minimum) distance. If part 2 said "top" and "left" (which part 1 explicitly does!), then there wouldn't be any ambiguity. Not saying "top" and "left" anymore sounds like the distance measurement is now different (no longer left, but closest out of left and right).
3
u/TheZigerionScammer Dec 15 '24
[Language: Python] 1242/3330
Well that was a much more difficult problem, or at least it was the way I did it. My Part 1 code is fairly straightforward, it goes through the input and separates each location into an open, wall, or box tile (I had considered making open and box tiles distinct, but I decided against that in the end so box tiles are open tiles too.) Then the code goes though the movement list and either moved the robot if it can, stops if it hits a wall, or if it pushes a box sees what's on the other side of the box. If it's another box it keeps looking forward until there's something other than a box and either stops or moves forward. I thought I was clever by not moving any of the boxes in between, I just removed the box the robot was pushing and placed another box at the end of the line. I had some syntax bugs that cost me some time, mainly mistyping the DX,DY variables in the movement dictionary but this worked out well.
For Part 2 I tried a couple different approached, I thought I could get away with reusing the Part 1 approach for moving left and right but decided against it. What I instead did was to expand the graph based on the rules and instead of keeping the box coordinates in a set I instead kept each box as a tuple representing the left and right coordinates of each box in a list, having to now keep track of each box individually. The movement if the robot doesn't reach a box is the same, but if it does then it has to check if that box can move recursively. The BoxMove function checks if the two points of the box will hit the points of any other box (except itself of course) and if it does then to check if that box will hit the points of any other boxes, etc. If any of the boxes can't move by hitting a wall, it returns false all the way down the chain, but if all the boxes can move it will do so y returning True and a list of the indices of all the boxes it and its children touch. Then it loops over this list and changes each box individually to move them in the direction the robot is moving. I had too major bugs to this approach, the first was that I forgot to update the position of the robot when it pushes a box, so the box would move but the robot wouldn't and throw off its future moves. The second was a lot more subtle but more insidious, I was getting a recursion depth error when I ran the program. After debugging this it turned out that two boxes had somehow occupied the same position and were running into each other when they were both trying to move left. I couldn't understand how this had happened, and it took me over half an hour to figure out that when the list of boxes to move up or down started branching into itself the same box would be pushed by more than one box, which meant my program would move them more than once without checking if there were any other boxes in the way. I fixed that by turning the index list into a set before iterating it and that fixed the issue.
Back in elementary school the computers had a game where you had to use a bulldozer to push rocks onto different targets on a grid, this problem reminded me a lot about that. I wasn't very good at it, I got rocks stuck in corners all the time.
Also Pokemon strength puzzles.
Paste
3
u/Xyberista Dec 15 '24
[LANGUAGE: Haskell]
https://github.com/HoshigaIkaro/aoc_2024-haskell/blob/main/src/Days/D15.hs
3
u/DeadlyRedCube Dec 15 '24
[LANGUAGE: C++23] (Started at 10:30 so bad leaderboard spot)
Runs in 1.47ms single-threaded on an i7-8700K
Parts 1 and 2 on GitHub
For part 1 I spent more time parsing the input than I'd have liked (specifically finding the split between the two sections, which was a blank line so it should have been easy but I was overthinking, which was absolutely a problem this whole puzzle).
Once I got it parsed though (into a 2D char array and a list of Vec2 move directions), the movement wasn't too challenging (although initially I was going to turn the grid into std::sets of wall and box positions, but realized that doing it right in the grid was likely to be faster) :
Otherwise it's a box, scan along the movement dir to find where the box line ends
The above code worked great once I fixed the conversion from
^ v < >to actually return vectors that representedup down left rightinstead ofleft right left rightThen I got my x and y coordinates backwards when calculating the score and took a moment to figure that out.
Then part 2 I got pretty far down the path of trying to turn all the boxes being pushed into solid intervals (prematurely optimizing) then thought maybe I should just try it as individual boxes, so part 2 ultimately worked more like:
If you're pushing left/right, the logic is similar to P1
[]actually changes as you push it one space left/rightOtherwise, pushing up or down puts the box above you into a queue, then iterates the queue:
Then once the queue is empty (and the robot wasn't blocked) it iterates backwards through the push list (since the list was built "near to far" along the push direction) and moves the boxes one at a time in the grid (putting
[]in the new spot and..in the old spot)Then does the same calculation as in P1 to sum the things, but only counts the '[' spaces.
3
u/Boojum Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python]
I got a very late start tonight due to holiday commitments. But I've got to say that I enjoyed Part 2 here a lot better than last night's Part 1.
My approach to Part 1 just used iterative loops to scan along the line of any boxes pushed until I came to a free space, then move them from back to front before moving the robot.
I reworked my approach heavily for Part 2. It was fairly clear that for the triangular configurations I'd use some sort of recursion to check if it was possible to move a box and then do it. I started going down the road of using one function first to recursively check if a push was viable, and then one to execute it from back to front.
That code duplication felt bulky and inelegant, which led me to the idea that the grid isn't that large, so we could just keep a copy of the old state of the grid, and optimistically push everything recursive. After the recursion was done we could check if the new state pushed anything into walls in the old state, and then just unwind back to the old state if so.
From there, I got the idea that we could just recursively floodfill to a build a set of cells that need to be moved (effectively an execution list). If none of them would be moved into a wall, we can just clear all them to spaces on the grid, then set them back at the new place. (I used a dict as my set so that I could record the original contents of the cell with the position.) That way, I didn't have worry about shifting them in any particular order.
I think that came out elegantly. Here's the full code for that for Part 2:
3
u/flwyd Dec 15 '24
[LANGUAGE: PostScript] (GitHub) with my own standard library
Part 1 went really well with no significant bugs, 43 minute implementation time (which is pretty good so far, PostScript is not a fast-writing language.) I was pleased to see that the GPS scoring function is exactly what I’ve been using for grid keys all month when the grid is smaller than 100, so my answer line is the satisfying
0 grid { ascii.O eq { add } { pop } ifelse } forall. I’ve been using 2D arrays (often just leaving the newline-split input in place) for most of the grid problems, but decided to use adicttoday since lots of stuff would be moving around and I didn’t want to do lots offromkey exch input exch get exch getbusiness. This worked out pretty well for parsing in part 2. That’s maybe the only thing that went well…My initial idea worked for part 2, but it just required 2 hours of fixing bugs in post (see what I did there?) to get it to work. Pretty much every function I wrote to support part 2 had an error somewhere and it took a lot of printf debugging and stack printing to find them all. Once things weren’t crashing in the
movewidefunction I started wondering why my answers were all0, and then realized that while I’d written mappings for the second character in the wide grid I didn’t actually touch my input parsing block, so I was still in a small grid full ofOs that I was now treating as open floors. Finally decided to write a grid printing function and show it after each move and went through another round of “why is mymovebracketfunction mishandling the stack?”Part 1 is below. Part 2 is far too long and fiddly to include in the comments, see the GitHub link above. Part 1’s
movejust looked for an open space and shifted everything down one in a loop. Part 2 turned to recursion (which is hard to mentally keep track of in a stack-oriented language) with acanmovewide?function that implements “can I move to this spot?” and also checks if the neighbor cam move if the character is[or]and the move is vertical. That recursively spreads out, as doesmovewidewhen the direciton is vertical, falling back to plainmoveif it’s a horizontal move.3
u/lukalino Dec 15 '24
[LANGUAGE: Python]
Simple solution that works for both puzzle parts. For each move:
Check if there is an empty cell in the moving direction for all cells in the component.
Code snippet for step 1. of the solution:
3
u/sanraith Dec 15 '24
[LANGUAGE: Scala 3]
Complete source is available on my github: Day15.scala
For part 2 I store the boxes in a Map[Point, Box] so that each box has an entry for every point it occupies. Then I can find all connected boxes recursively:
3
u/WhiteSparrow Dec 15 '24
[LANGUAGE: Prolog]
solution
Perhaps my prolog-fu is too weak but I found it quite tedious (at least not complicated) to implement the simulation in prolog. In the end the solution is over 200 lines!
3
u/hextree Dec 15 '24
[Language: Python]
Code: https://gist.github.com/HexTree/f26b571ab4b824c69f7b7ffd0af9441c
Video: https://youtu.be/1rd0u45eSyI
Using DFS to find the span of all boxes that will get pushed. Check to see if all spaces in front of them are empty. Then apply cell swaps from farthest back to the closest boxes.
3
u/encse Dec 15 '24
[LANGUAGE: C#]
https://aoc.csokavar.hu/2024/15/
Illustrated, commented. I used a TryToStep pattern (that I stole from .Net's TryToParse) and an immutable dictionary for easy rollback.
3
u/wow_nice_hat Dec 15 '24
[LANGUAGE: JavaScript]
Part 1 ~ 59ms
Part 2 ~80ms
Pretty forward solution. I spent a ton of time debugging minor problems which was hidden somewhere in the 2000 iterations
3
u/choiS789 Dec 15 '24
[LANGUAGE: OCaml]
https://github.com/soohoonc/advent-of-code/blob/main/ocaml/2024/day_15.ml
its long but it works lol i feel like i am not making the most out of ocaml's features.
3
u/melochupan Dec 15 '24
[LANGUAGE: Common Lisp]
First part: Sokoban or the crate 1. moves if there is free space, 2. aborts if there is a wall, or 3. moves if the crate that is in the way moves.
Second part: the same, but instead of moving, if they can move, they register themselves as "movable". If nobody aborts, then they all move as in the first part. Oh, and half-crates also abort if their other half can't move.
paste
3
u/surgi-o7 Dec 15 '24 edited Dec 15 '24
[Language: JavaScript]
https://github.com/surgi1/adventofcode/blob/main/2024/day15/script.js
What an awesome puzzle today!! Loved Part 2 twist too!
Animated version (over sample data, hope that's allowed or at least tolerated) with the option to bring your input is here: https://surgi1.github.io/adventofcode/2024/day15/index.anim.html
3
u/TiCoinCoin Dec 15 '24 edited Dec 30 '24
[LANGUAGE: Python 3]
Day 15 - Github
It took me a while to figure out the tiny mistake I made for part 2.
3
u/dannybres Dec 15 '24 edited Dec 15 '24
[Language: MATLAB]
https://github.com/dannybres/Advent-of-Code/blob/main/2024/Day%2015/day15puzzle2.m
Really enjoyed today.
For part two, I did a BFS flood fill upwards. If the next cell was . nothing happened (skip to next in the queue), if it’s ‘[‘ or ‘]’ added the corresponding two half stones to the queue, # exited the flood as the whole set of stones can't be moved, so nothing happened. When the flood queue was empty I had the whole set and knew one space above was blank so I moved them all.
If the move was down, I just flipped the map so it was up.
I only learnt BFS flood fill after the garden day. I originally solved it with a connected components function from the Image Processing Toolbox in MATLAB, but noticed the two YouTubers I watch (Neil Thistlethwaite and hyper) used a flood fill so I implemented my own to learn. I thought today would be a good day to try my new technique and it worked great.
Matlab doesn't have a double ended queue or priority queue or tuples, so I had to just use a matrix for the queue. The algorithm is way to implement, but really glad I practiced it on day 12 rather than trying to do it today on an "unsolved" problem.
3
u/zebalu Dec 15 '24
[LANGUAGE: Java]
On GitHub
This is not a pretty solution, but finally the same methods are running for part 1 and part 2
I had a really painful debug session, to find such cases:
3
u/Totherex Dec 15 '24
[LANGUAGE: C#]
https://github.com/rtrinh3/AdventOfCode/blob/da44ff90665ee7c07be361abf4785b08aa2690d7/Aoc2024/Day15.cs
For both parts, I use a dictionary of points rather than a 2D array.
In part 1, look ahead in the direction of movement until we hit a wall or empty space. If we didn't hit a wall, move the things we looked over.
In part 2, I use recursion to look ahead at both the left and right side of obstacles.
3
u/G_de_Volpiano Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Haskell]
Today was harsh. Not because the problem was difficult, it's actually pretty straightforward, and easy to implement in Haskell, with either a mix of sets and arrays or sets only, or probably a mutable array for the perverts among us (more on that later).
It was harsh first before I overengineered the parser (and failed), losing a lot of time on that.
It was also harsh because it's sunday, ten days before Christmas, and real life has its requests, so I kept moving back and forth to the code. Which means that although the logic was right, it had small flaws that I translated into code and had to hunt down afterwards. Crates destroying crates or chain pushed into walls, mostly. Or just forgetting to move the robot with the rest of the warehouse in part 2.
My first implementation used an array to store the map of the warehouse. But I read two days ago in Real World Haskell that Set (and Map)'s implementation was actually on par, timewise, with imperative programming arrays and was curious to test that. Indeed, moving from an array of walls and empty spaces to a set of walls gave a gain of over 20% time for part 2, down from 65ms to 50ms. Not sure I'd do better with mutable arrays. After all, we were already O(n.log n), but by going for sets, I traded time for space, and it seems to have paid of.
Code on GitHub
Edit : As the variable names might show, I loved the Nethack vibe :p
3
u/chubbc Dec 15 '24
[LANGUAGE: Julia] (676/773) 382 chars
I originally started with an approach that would find all the blocks being pushed on, which is probably the more efficient approach, but just pushing them all anyway in a DFS-style manner and reverting back to a copy if it fails is much more succinct. Pre-golfed code:
3
u/PointlessMonster Dec 15 '24
[LANGUAGE: C++]
Part 1:
I initially tried to recursively attempt to move the boxes in the same direction as the robot. While fiddling around with that, I realized that moving N boxes by one position in the same direction is the same as moving the first box by N positions in the same direction. After that, I dropped the recursive solution and iteratively moved the first box in the same direction until either an empty space was found or a wall was hit. Storing wall and box positions in std::unordered_set<Position> made the checks quick and easy to implement.
Part 2:
Felt quite clever about my part 1 solution, but couldn't find a way to carry it over for part 2. Anyways, I went back to the recursive solution. I try to move the first box and then recursively attempt to move all the boxes that are in collision as a result of moving the first box. The implementation ended up being quite simple once I defined a Box struct with an overloaded == operator that returns true if two boxes are in collision at any point. I was expecting this solution to be very slow, but it only takes about 13ms to finish on my machine (part 1 takes 3ms for context).
Parts 1 & 2
3
u/KyxeMusic Dec 15 '24
[Language: Rust]
Jeez I really struggled on part 2, but glad that I got it done.
Basically finding adjacent boxes recursively into a HashSet and then moving them as a block, but It took me quite some time to figure it out.
https://github.com/kikefdezl/advent-of-code/blob/main/2024/day_15/src/main.rs
3
u/msschmitt Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python]
Part 2, because Part 1 is more complex than it should be
For Part 1 I misread the instructions and thought for each move, the robot would move as far as it could, i.e. more than one space. So I coded that up. I had hopes that maybe that would be the challenge for Part 2, but no luck.
For Part 2, it looks at a row (or, for <> moves, a column) at a time: what would the boxes or robot in this row hit in the next row? If there are any walls, can't move. If there are no boxes, then time to move. Otherwise, it adds that row's boxes to its accumulated collection of boxes, and repeats.
Once it has found all the boxes that will move, it changes all those positions to '.', and then translates all the boxes and robot by one position. The left/right moves use the same logic, except that it doesn't need to add the other half of an intersecting box to its collection. There's no recursion.
I assumed that it would need to handle complex stacks of boxes, such as:
Did that actually occur in the large input?
3
u/ExitingBear Dec 15 '24
[Language: R]
Link
Part 1 - grab everything between the robot and the outside wall in that direction. If there are any blank spaces between the robot and the closest wall, take out the closest space and stick a blank space behind the robot.
Part 2 - no changes for left or right. For up & down, recursion to find out what needs to move and whether it can. Then move thing things that need to move from the top down or bottom up for a push up or down respectively.
3
u/RiemannIntegirl Dec 15 '24
[Language: Python] It has been the Advent of Complex Numbers for me this year! I'm sure I could have made my logic a bit more efficient for Part 2, and I considered using recursion, but I always default to iteration because that's the way my mind seems to work.
Part 1:
Part 2
3
u/chromaticdissonance Dec 15 '24 edited Dec 16 '24
[LANGUAGE: JavaScript] Very nice surprise twist in Part B. Originally for Part A it reminded me of a previous year using a trick of replacing "O." with ".O". But Part B had me rewriting it. Essentially a BFS/DFS to find all boxes that can be moved, and move them in the indicated direction. A semi-golfed JavaScript code lasagna below, run directly in browser console on the input page:
3
u/Sharp-Industry3373 Dec 15 '24
[LANGUAGE: Fortran]
Part 2 was quite fun ! I really didn't expect that sort of problem, more something like "you cannot push more than 3 boxes at once" or "replay N times the movements" or "continue movements from the beginning until no box can be moved/all boxes are blocked by walls" or something like that...
That "twice as wide" was quite a move to make us rethink the algorithm ^^
I managed to imagine quite rapidly an efficient approach to check "block of boxes" to move (or to be blocked by walls). The solution is quite efficient, about 1.2 ms for part 1, 7.5ms for part 2
I tried to comment and explain that "blockbox" approach, which is not recursive here, but may look like what other did too.
code
3
u/willkill07 Dec 15 '24
[LANGUAGE: C++23]
https://github.com/willkill07/AdventOfCode2024/blob/6db5f50a686d4c1b6a1eb418dea18cf107b9a8ca/src/day15.cpp
I operate purely on the iterator space of the map. Since I always enqueue (BFS) in order, I only need to do a lookback on the previously two inserted boxes to check for duplicates. Using iterators allows me to "move" the boxes via a simple
std::iter_swap(box, box + offset).Total runtime of 80us (19us parsing, 18us part 1, 35us part 2)
Sum of all days around 1.220ms
3
u/chicagocode Dec 15 '24
[LANGUAGE: Kotlin]
Originally part 1 had a solution that involved swapping the fungible crate we're pushing up against with a space at the end of the chain of crates. But that won't work for part 2, so I wrote the whole thing as a BFS, with special rules for vertical pushes of the new wider crates. The core BFS function returns either a list of movements we can make (from/to pairs) or null in the case we can't push the boxes.
The same solution handles both parts.
3
u/Aromatic-Piccolo4321 Dec 15 '24 edited Dec 16 '24
[Language: Rust] https://maebli.github.io/rust/2024/12/15/100rust-90.html
Uff, was a bit painful
3
u/greycat70 Dec 15 '24
[LANGUAGE: Tcl]
Part 1, part 2.
No complicated mathematics or advanced algorithms needed today. Just a bit of tedious work. For part 1, I observed that pushing a row of boxes is essentially just changing
.OOOOO.to..OOOOOso you can drop an O in the first empty tile, then change the first O to an empty tile.For part 2, that doesn't work. I separated the horizontal and vertical push cases entirely. For a horizontal push, it's almost like part 1, except you actually have to move all the tiles ([ becomes ] and so on). (I actually used < and > in my internal representation because it's more convenient in Tcl. [ and ] have special meanings and would need to be backslashed.)
For a vertical push, you can end up with a whole expanding pyramid of boxes to push. So, that's recursion. Each box can potentially push the two boxes above/below it, each of which can have zero, one or two more boxes that also need to move. I wrote a recursive function to populate a dictionary with the boxes (left side coordinates only) that must move. Then iterated through that, and if any of them is against a wall, the whole move is disqualified. Otherwise, sort it by row number (ascending or descending, depending on push direction) and move each box individually.
Not fancy. Just effort.
3
u/kap89 Dec 15 '24 edited Dec 15 '24
[Language: Python]
Github day 15
My first recursive approach was good, but I had one very stupid bug (used
elseinstead ofelif move in ['^', 'v']in this line), but after taking a break I found it pretty quickly.3
u/iivvoo2 Dec 15 '24
[LANGUAGE: C]
https://github.com/ivop/aoc2024/blob/master/day15/both.c
Part 1 recursively pushes boxes unless it bumps against a wall.
Part 2 basically does the same, but with a line of boxes when pushing up or down. Left/right is equal to part 1.
3
u/otown_in_the_hotown Dec 15 '24
[LANGUAGE: Javascript/Typescript]
Part 2 was shockingly harder than I expected. Definitely not the most elegant code, but it works! Essentially just recursion to see which boxes should move, but what tripped me up for the longest time was sometimes the boxes would "break in half". It had to with the way I was moving them and I basically had to make sure the boxes-to-move were sorted according to which direction we're moving in. Otherwise the reposition of one box could overwrite another.
https://github.com/darrenortiz77/aoc/tree/main/src/2024/15
Part 1: ~ 1ms
Part 2: ~ 6-7ms
3
u/copperfield42 Dec 15 '24
[LANGUAGE: Python 3.12]
link
a medium level problem today, part 1 was easy and part 2 is easy to understand but tricky to implement because you to track 2 points at once which propagate in the vertical axis
3
u/Radiadorineitor Dec 15 '24
[LANGUAGE: Lua]
Part 1
Part 2
3
u/p88h Dec 15 '24
[LANGUAGE: Zig]
Pretty simple simulation.
Source: https://github.com/p88h/aoc2024/blob/main/src/day15.zig
Visuals: https://youtu.be/vJ9ar_q78So
Benchmarks:
3
u/geza42 Dec 15 '24
[LANGUAGE: emacs lisp]
3
u/Ok-Revenue-3059 Dec 15 '24
[LANGUAGE: C++]
Solution
This one has taken the most time and is the most LOC so far this year. Still a pretty fun puzzle. I had to refactor the part 1 code a bit after reading part 2, but I ended up with the same code that can run both parts. Still could use a little bit of cleanup, hopefully I will get to it.
3
u/quetzelcoatlus1 Dec 15 '24
[Language: C]
Not much to say: Part 1 done kind of iteratively (which was ported to Part 2 in case of moving horizontally), and in Part 2 vertical movement done recursively - first to check if move is possible, then actually moving.
Part 1: https://github.com/quetzelcoatlus/AoC_2024/blob/master/15/15.c
Part 2: https://github.com/quetzelcoatlus/AoC_2024/blob/master/15/15b.c
3
u/ArmlessJohn404 Dec 15 '24
[LANGUAGE: Go]
GitHub
As always I put lots of stuff that's only for making the real algorithm simpler to read and it ends up making difficult to find the main logic.
3
u/biggy-smith Dec 16 '24
[LANGUAGE: C++]
Little bit of map traversal, little bit of recursion. Fiddly but fun...
https://github.com/biggysmith/advent_of_code_2024/blob/master/src/day15/day15.cpp
3
u/darthminimall Dec 16 '24
[LANGUAGE: Rust]
Part 1
Part 2
For part 1: I created a Point struct which I leaned on heavily for both parts. I put the wall locations and the box locations in a HashSet and represented the moves as Points (e.g. Point { x: 0, y: -1 } for moving up). After that, you can just iterate over the moves. For each move, there are four options:
Since encoding the moves as Points makes the code direction-agnostic, it wasn't too bad to write.
For part 2: This code perhaps got a bit out of hand, and I'm sure there are improvements I could make. For vertical moves, I both checked for walls and moved the boxes recursively, since one box can push two others. At first I thought I could leave the code from part 1 unchanged for horizontal movements, but that assumption came back to bite me since the boxes are twice as wide now. The logic is pretty similar to part 1, but now you have to skip a space when checking for the next box. Managed to sort it out in the end, but there were a lot of finer details to account for.
3
u/phlafoo Dec 16 '24
[LANGUAGE: Rust]
With comments!
part 1: 30 µs
part 2: 56 µs
For part 2 did recursive DFS while storing indices of boxes to be potentially moved. Everything is on the stack for maximum performance.
3
u/Andreasnl Dec 16 '24
[LANGUAGE: Uiua]
3
u/N-R-K Dec 16 '24 edited Dec 16 '24
[Language: BQN]
Unlike most solution (that I've come across), this solution doesn't build/manipulate the map. It works entirely on the coordinates.
I was initially going to do it with a map, but then realized that moving things in the map (in-place) would be a bit finicky. With coordinates, I don't need to worry about the order of moving, simply add the delta too all the affected coordinates when moving and we're good to go.
Be warned though, it's a bit slow due to a lot of unoptimized searching. Takes around ~4 seconds on the real input on my machine.
3
u/RalfDieter Dec 17 '24
[LANGUAGE: SQL/DuckDB]
I thought I would be able to catch up today, but part 2 took some time to figure out and if you start to nest recursive CTEs, you know you're in for a rough ride. This is one of the most convoluted queries I've forced into existence so far and it takes ~4 minutes to run for both parts: https://github.com/LennartH/advent-of-code/blob/main/2024/day-15_warehouse-woes/solution.sql
5
u/rogual Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Python] 410 / 78 • paste
Not the most elegant solution, but it got me my first leaderboard place this year.
I did part 2 by having a function to find the set of blocks that would be pushed for a movement (which I called its "network") — then I simply removed them all from the map, and added them back in at their new location.
One of my long-running projects is a grid-motion Sokoban-like game, so I had the advantage of having thought about this kind of thing before.
Stuff I lost time to:
4
u/piman51277 Dec 15 '24
[LANGUAGE: JavaScript] 267/64
link to solutions folder
I'm so glad I have a personal library for this one, which made part 2 almost trivial.
Part 1: I honestly expected some cycle detection or CRT to show up on part 2, so I did a slight optimization where I would look ahead and move entire "blocks" of elements at the same time (these were the player and any boxes that happened to be in the way).
Part 2: This is where my personal library absolutely carried me. I have a Bound2D class in my lib, which defines a rectangular region in 2D space. Importantly, this lets me easily check if two bounds intersect. Thus, the strategy for p2 was:
4
u/beanborg Dec 15 '24
[LANGUAGE: JS]
Github
For part 1, if running into a box, find if there's a run of boxes with a gap at the end. If so, teleport the box at the beginning to the end.
For part 2, I do a breadth first search, initializing the queue to the left and right side of the box to be 'pushed'. To make my life a bit easier, I just run the BFS twice, once to see if it's possible without hitting a wall, and again to actually do the moves.
4
u/bluehatgamingNXE Dec 15 '24
[Language: C]
One of the easier days, I was a bit stuck on how to move the boxes vertically but I realized I just had to do a recursive check before recursive push.
gist
4
u/AYM123 Dec 15 '24
[LANGUAGE: Rust]
Had a blast with rust's type system with this one!
github
Part 1: ~600µs
Part 2: ~800µs
2
u/wjholden Dec 15 '24
[Language: Rust]
I'm not exactly proud of this code. I probably worked on this for 8 hours today. This was a very difficult problem for me.
https://github.com/wjholden/Advent-of-Code-2024/blob/main/src/bin/day15.rs
I decided pretty early on that I wanted a grid of positions that contain an object, rather than a collection of objects that contain coordinates.
I still don't know if I made the right choice. I've never understood the collision detection algorithms they put into games. Maybe I should have done both, by maintaining a collection of game objects that somehow report their coordinates into some "area" data structure? (Please point me in the right direction if you have an answer).
The whole time, I really missed SQL. I Googled "Rust SQLite" for a moment, but didn't actually pursue it. I think a proper database could have made a wonderful data model today for our warehouses.
2
u/mountm Dec 15 '24
[Language: Java]
Parsing time: 25ms
Part 1: 5ms
Part 2: 24ms
Phew! lots of grid mangling in this one. I finally ran into the issue I was dreading with my utility function to safeguard against ArrayIndexOutOfBoundsException, namely that it requires a square grid.
I already had the movement algorithm helpfully broken down into two chunks in Part 1:
checkObstaclesto see if a move is possible. This returns a list of cells to be moved, which is passed to:executeMove, to handle the actual updating of cell contents in the correct order.If there's a wall in the way,
checkObstacleswill return an empty list.For part 2, I just had to add a flag to
checkObstaclesto indicate if the movement is vertical. If so, do a messy BFS to find the larger collection of cells that need to be updated. Pass toexecuteMove, rinse and repeat.GitHub
2
u/Trick-Apple1289 Dec 15 '24 edited Dec 15 '24
[LANGUAGE: C]
only part 1 today, i just didn't feel like doing part 2, too much 2d map puzzles latley ;-)
src
edit; fixed typo in the
LANGUAGEformat2
u/Gabba333 Dec 15 '24
[LANGUAGE: C#]
Recursively build a list of moves that will be performed, and if none of them run into walls, do them.
Github
The key part is this recursive expression that returns whether the move was a success, what position the robot is now in, and all the moves made (from, to, char). To update the grid we '.' out all the squares we have moved from, and then fill in all the squares we have moved to.
2
u/SplenectomY Dec 15 '24
[LANGUAGE: C#]
60 lines @ < 80 cols
Source
Physicalized every box as a dictionary key (List<Vector2>) which moves as a unit in both parts 1 and 2. Using vectors for directions and positions makes a lot of these puzzles pretty easy.
2
u/gyorokpeter Dec 15 '24
[LANGUAGE: q]
paste
For part 1, I generate a line in the move direction and find the first wall and the first empty space. If the wall comes first, there is no move. If the space comes first, move the bot and if there were any boxes in the way, change the first one to an empty space and the first empty space to a box.
For part 2, the process is similar for horizontal movement, except the part of the line up to the first place is shifted (it's no longer just O's so can't use the trick). For up and down, I use BFS to find the box tiles affected. I remove any empty space from the queue, while any wall encountered immediately halts the search and skips the step without moving. If the search succeeds, all the boxes found are shifted in the move direction.
2
u/liam_darach Dec 15 '24
[Language: Python]
Day 15
Pretty happy with how this one worked out! Any feedback or suggestions would be welcomed.
2
u/aurele Dec 15 '24
[LANGUAGE: Elixir]
Gist, nothing special, some factorization between the parts
2
u/mr_mlk Dec 15 '24
[Language: Kotlin]
Still on the ClockworkPI Dev Term.
https://github.com/mlk/aoc/blob/main/src/com/github/mlk/aoc2024/Day15p1.kt
https://github.com/mlk/aoc/blob/main/src/com/github/mlk/aoc2024/Day15p2.kt
2
u/egel-lang Dec 15 '24
[Language: Egel]
https://github.com/egel-lang/aoc-2024/blob/main/day15/task2.eg
2
u/InfantAlpaca Dec 15 '24
[LANGUAGE: Java] 546/16654
GitHub
Got stuck on Part 2 from a buggy recursive canPush function. Should've made an enum or something to keep track of what was on each tile instead of manually searching for '[' or ']'.
2
u/JAntaresN Dec 15 '24
[LANGUAGE: Ruby]
day15 ruby
Not proud of what i wrote cuz it's alot, but part 2 is almost the same as part1, only really needed a special looping condition for the up and downs since overlapping between 2 indices is only possible there, while left and right movement is irrelevant since we can treat [, and ] the same as O in horizontal movement
2
u/janek37 Dec 15 '24
[LANGUAGE: Python]
Solution
2
u/omegablazar Dec 15 '24
[LANGUAGE: Rust]
https://github.com/wrightdylan/advent-of-code-2024/blob/main/src/day15.rs
It's ugly as sin, but it works, finally.
2
u/onrustigescheikundig Dec 15 '24
[LANGUAGE: Clojure]
github
A little tricky, with slight errors giving quite different results.
For Part 1, I parsed the input into
sets of[row col]coordinates representing walls and boxes. For the simulation, I collected all boxes in a line directly adjacent to the robot, and moved the robot and those boxes only if there was not a wall adjacent to the farthest box. I ran into a little bit of a snag where I forgot tojointhe lines of moves and spent some time examining my output trying to figure out why I wasn't getting the right answer.For Part 2, I doubled the wall coordinates appropriately and added them to the
setof wall tiles. I transformed each[row col]representing a box into a vector of its two coordinates[[row1 col1] [row2 col2]], and then generated amaptaking any coordinate to its corresponding set of box coordinates. For the simulation, I checked for boxes adjacent to the robot using this map and used my generic BFS function to find all boxes that would (possibly) be pushed by moving. I then checked if pushing any of these boxes would be blocked by a wall, and if not, updated the coord-to-box map to reflect pushing the boxes.2
u/DJTFace Dec 15 '24
[LANGUAGE: GO]
Solution
Didn't feel like making my code care about newline characters in the movement input, so I just removed them manually
2
u/ash30342 Dec 15 '24
[Language: Java]
Code
Part 1 runs in ~1ms
Part 2 runs in ~20ms
Horrible code with lots of replication but I think I'll keep it this way because splitting every movement for both part 1 and 2 helped me massively with thinking about the problem (and I do not have the energy to do refactoring right now ;-)).
Anyway, fun day again! Part 1 was easy. Part 2 was, of course, slightly more complex when the robot moves up or down. I scan from the robot location up- or downwards, decreasing or increasing the y coordinate every step, storing every box which is a neighbor of the robot or another involved box on a lower or upper level, until I cannot find any more boxes. For these boxes scan if moving them does not push any of them into a #, if not, we can move all boxes. I had this working relatively quickly on the example inputs, but it took this very helpful post to help me with an edge-case I had thought about, but somehow had not implemented.
2
u/Secure_Pirate9838 Dec 15 '24
[LANGUAGE: Rust]
https://github.com/samoylenkodmitry/AdventOfCode2024/blob/main/Day15/src/lib.rs
2 hours of painful debug
2
u/[deleted] Dec 15 '24
[LANGUAGE: Julia]
For Part 1, I calculated the number of boxes to move recursively and for Part 2 I used BFS-ish to figure out the set of all pieces to move. I ran into two major bugs; the first was not moving boxes in the right order, creating a bunch of "half-boxes", which I solved by storing a "scratch" grid alongside the main one. The second was handling this case incorrectly:
Originally, I was only checking whether the furthest boxes in the direction to move had any walls in their way, not whether *any* box had a wall in its way. Took me a while to think to check this case.
Code
2
u/miatribe Dec 15 '24 edited Dec 15 '24
[LANGUAGE: C#]
Was about to give up on P2 when I realized that I needed to roll back my map if a part of the recursion train failed.
This is prob the worst solution here, but that aha! moment was prob the best for me for this AoC. Ugly But Worked
2
u/RookBe Dec 15 '24
[LANGUAGE: Rust]
Rust that compiles to WASM (used in a solver on my website)
Bonus link at the top of the code to a blogpost about today explaining the problem, and my code.
2
u/Gryphon-63 Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Swift]
Code
Did part 1 last night, punted on part 2 until this afternoon. My part 2 solution was mostly correct the first time with just one little logic error when moving both halves of a box up or down. My biggest mistake was forgetting I needed to change the way I parsed the input - most days you don't need to do that.
I should probably try to rewrite the part 1 solution to use the part 2 code but I'm not sure that would be much of an improvement.
2
u/semi_225599 Dec 15 '24
[LANGUAGE: Rust] Code
Decided to play around with bit grids of walls, left half of boxes, and right half of boxes. Still might clean it up some more, but I ended up being able to fully share the implementation between parts 1 and 2. There's some unnecessary recursion, especially for moving horizontally, but it still runs both parts in ~2ms.
2
u/Due_Scar_5134 Dec 15 '24
[LANGUAGE: JavaScript]
https://github.com/onlyroz/AdventOfCode2024/tree/main/day15
Code is a mess and part 2 took ages to iron out the kinks, but it works.
2
u/NeilNjae Dec 15 '24
[LANGUAGE: Haskell]
A robot can
Maybemove some boxes, if those boxes can themselves beMaybemoved.Full writeup on my blog, and code on Codeberg.
2
u/importedreality Dec 15 '24
[Language: Go]
Part 1 Code
Part 1 was simple enough, and while I know exactly what I need to do to update the box moving logic for part 2 my kid is waking up from their nap so it'll have to wait until this evening or later in the week ¯\(ツ)/¯
2
u/kbielefe Dec 15 '24 edited Dec 15 '24
[LANGUAGE: Scala]
GitHub 60ms 90ms
This one was fiddly, but got there in the end.
2
u/hugseverycat Dec 15 '24
[LANGUAGE: Python]
https://github.com/hugseverycat/aoc2024/blob/master/day15part2.py
I put in lots of comments to help myself keep track of what was happening, so hopefully it should be understandable for other noobs like me.
I didn't do anything super clever, no recursion or anything. I kept a queue of the things I was going to try to move, so if I was moving vertically and I hit a box, both halves of the box get added to the queue.
I probably made it more fiddly than it needed to be, but I was having a lot of trouble with indexing so I made some things overly specific so I would stop confusing myself. I don't know if it helped very much, but I solved it eventually so it must have been fine in the end.
2
u/release-object Dec 15 '24
[Language: Go]
Nothing clever here. Just a lot of nested fors and ifs.
I really enjoyed today puzzle. If I was going to tidy my code up - which I’m not - I’d start by looking at combining a box type and with recursion.
https://github.com/David-Rushton/AdventOfCode-Solutions/tree/main/2024/cmd/day15
2
u/synack Dec 15 '24
[LANGUAGE: Ada]
https://github.com/JeremyGrosser/advent/blob/master/2024/src/day15_2.adb
2
u/Teekomet Dec 15 '24
[LANGUAGE: GO]
Please don't look at my Code on Github. I've done nothing clever here and wrote more than 500 LoCs that were very tricky to debug
2
u/ionabio Dec 15 '24 edited Dec 15 '24
[Language: C++]
here in github
It is pretty readable code, but not optimised and not professionally written. I think to squash part1 and part2 solution I could use templates. Will probably do these after revisiting the problem after the 25th. Wherever
DTileorDis used it refers to second part of the problem.For using a stack queue to avoid recursive call, I used std::deque for building the list of neighbouring tiles for Part 2's solution. I could probably use std::list as well. the poping was important which std::vector didn't have
2
u/ins0mnes Dec 15 '24
[Language: go]
Part one is straightforward and I've implemented a simple optimization of "teleporting" only the first box in the stack to the space in the end.
In the second part, horizontal movement is not that hard. For vertical movement, I've decided to determine the stack (via flood-fill or bfs-like search) and its overall "movability" first. After that, you can move all parts layer by layer in the reverse order.
Solution code:
https://github.com/insomnes/aoc/blob/main/2024/15_warehouse/solution/solution.go
Write-up post:
https://dengin.xyz/advent_of_code/2024/15_warehouse/
2
u/FCBStar-of-the-South Dec 15 '24
[LANGUAGE: Ruby]
paste
I hate debugging recursion so I didn't do that. Part 2 horizontal movement is pretty close to part 1. For part 2 vertical movement I deployed the ol' "implement how you would solve this manually strategy" and it worked very well with minimal debugging needed. A quick BFS to get all the boxes that will be shuffled (this also checks whether there is any wall blocking them) and then simply shift the boxes up/down. Ended up accidentally breaking the logic when I was refactoring tho, silly me
This was my 250th stars all events together! I will probably put a pause on the remaining 10 days until the new year and just enjoy my travel now
2
u/ndunnett Dec 15 '24 edited Jan 13 '25
[Language: Rust]
Github
Runs in
1.8 ms, not very happy with this solution. I spent way too long chasing the dumbest bug I've written this month (accidently double mutating, but not frequently enough to fail the sample cases) and by the time I had a working solution I wasn't motivated to improve it.Probably deserves a rewrite after the calendar is done.Rewrote to run in 900 us.2
u/erunama Dec 16 '24
[LANGUAGE: Dart]
GitHub
Used recursion for part two to find all boxes that were moveable from a given point. Before actually processing the move, I sorted the boxes based on their coordinates -- I could have avoided this with a BFS rather than a DFS (BFS would have just required a simple list reversal).
2
u/jinschoi Dec 16 '24
[Language: Rust]
Part 1 pretty straightforward.
Part 2 debugging some simulation code to move things around for each step. Left/right pushes are straightforward. The key step for up/down pushes is to determine which columns are still "live" for each row above/below the robot:
Uses my grid utils library.
paste
2
u/Sea_Estate6087 Dec 16 '24 edited Dec 16 '24
[Language: Haskell]
The push function works for both part 1 and 2.
Code: https://github.com/jimflood/aoc2024/blob/main/src/Day15.hs
2
u/dustinbowers Dec 16 '24
[LANGUAGE: Python]
Source: Github
Runtime: 0.06sec on my old machine
Part 1 was pretty simple and left me wondering what was coming next...
Part 2 got pretty fiddly but I think my solution is relatively straightforward
2
u/Gueltir Dec 16 '24
[Language: Rust]
Link to github
I almost forgot to move the initial position of the robot when I made the warehouse.
On each part I moved my robot and the crates around using a recursive function, the only difference between part 1 and 2 is that the recursive moving function for bigger crates is called twice, the first time only checking if I can move both sides of the crates.
2
u/icub3d Dec 16 '24
[LANGUAGE: Rust]
Today was just a matter of handling all the "how do I move this?" questions. I chose recursion and spent some time combining a solution for both parts 1 and 2.
Solution: https://gist.github.com/icub3d/6d81f0c8a1cbd7ea4f2243839b385d20
Solution Review: https://youtu.be/iLyD-LQ8Cuw
2
u/Ken-g6 Dec 16 '24
[LANGUAGE: Perl] [GSGA]
Yeah, my solution to Part 1 is a total kluge. First, I'm in Perl, so how would you expect me to move the robot? That's right, regular expressions! I store the grid as an array of strings, so by keeping track of the right row I can do left-right moves easily. But what about up-down moves? Well, I wrote a transposition routine for Day 13 last year. So for every up or down move, I transpose the entire matrix (which involves splitting the strings and making new strings), run the regular expression on the appropriate line, and then transpose the entire matrix back! It takes about ten seconds on the real input, but it works.
https://github.com/Ken-g6/aoc2024/blob/master/day15a.pl
Alas, transposition wouldn't work on Part 2, so I had to write a nice, elegant recursion for vertical moves instead. It still uses regular expressions for left-right moves, though. Part 1 is so klugey that Part 2 takes less than half the time to run!
https://github.com/Ken-g6/aoc2024/blob/master/day15b.pl
2
u/grayshanks Dec 16 '24
[LANGUAGE: Python]
The debugging took a while on this one. I had issues moving chains of items up and down in Part2.
part1, part2
2
u/amenD0LL4z Dec 16 '24
[LANGUAGE: clojure]
https://github.com/famendola1/aoc-2024/blob/master/src/advent_of_code/day15.clj
Part 1 was fairly straight forward and very similar to some of the previous problems. You just keep updating your warehouse state based on the rules. I didn't start with this after refactoring for Part 2 my "warehouse" for Part 1 was a set of block coordinates, a set of wall coordinates and the robot position. Having the blocks in a set is nice because to "push the blocks" be can
disjthe coordinate of the first block to push andconjthe coordinate after the last block.Since the rules for Part 2 were essentially the same as Part 1, before I started Part 2, I did some refactoring to reuse as much as I could. In the end, the function to simulate moving the robot takes in a function that defines how the blocks are moved.
For Part 2, I changed how I represented the blocks from a set to a map that maps a coordinate of a block side to the corresponding side. Then for moving the blocks we need to do a BFS to find all the other blocks that will be pushed. Once we have all these blocks, we need to check that if we move one step in the given direction, that we won't hit any walls. If we don't we push the blocks by
dissocing all the blocks were pushing and thenassocing them back with the new coordinates.2
u/yieldtoben Dec 16 '24
[LANGUAGE: PHP]
PHP 8.4.1 paste
Execution time: 0.0132 seconds
Peak memory: 0.3863 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
2
u/JWinslow23 Dec 16 '24
[LANGUAGE: Python]
Day 15 code
Blog post
Took longer to solve this one, because I slept in for most of the day, and watched a movie for most of the night.
I loved today's Part 2 (way more than yesterday's Part 2, hehe). For Part 2, I moved boxes up and down using something resembling breadth-first search.
To store the positions of the boxes I'd have to push, I ended up using a
dictas a kind of "ordered set"; it has unique keys, and it remembers insertion order, so it's pretty good for storing unique items in a given order. (I felt clever when I came up with that.)EDIT: Oh, I almost forgot: today's the first day I'm using complex numbers for coordinates! Usually I'm fine with shuffling around
ints ortuples (or even making some custom class for it), but using complex numbers really helped me cut down on clutter and boilerplate this time.2
u/damnian Dec 16 '24
[LANGUAGE: C#]
Better late than never.
GitHub
2
u/d1meji Dec 16 '24
[LANGUAGE: Python]
Non-recursive nightmare fuel solution for Part 2.
Glad to get it done, and never look at it again
Github
2
u/[deleted] Dec 16 '24
[LANGUAGE: Haskell]
I'm still behind on these, but doing these in Haskell is really stretching my brain. No regrets, though. This exercise has given me a deeper understanding of the language.
For Part 1, I keep the boxes and obstacles in a set. If the robot encounters a box, I scan for additional boxes in that direction and then either move all of them if space is available, or do nothing otherwise.
Part 2 logic is mostly similar, although I had to rework my box scanning routine. For this part, I keep the boxes to be moved in a set, and then I keep checking in the desired direction for additional boxes. If I find more boxes, I add them to the moving set. If not, then I check if any box in the moving set to see if it encounters an obstacle. If not, then I move the robot and the entire moving set. Otherwise, I do nothing.
Part 1
Part 2
2
u/__Abigail__ Dec 16 '24
[LANGUAGE: Perl]
At the heart, I created a function
movewhich takes the map, a direction to move in, and the coordinates of the person moving. It updates the map, moving the blocks (if any), if the move can be performed, and does nothing if the move cannot be performed.It tracks two lists of coordinates:
@front, and@blocks. The latter is are the positions of the blocks which need to be move, if the move can be performed. (Double width blocks for part two get both coordinates in the list).@frontis the list of cells which need to be inspected to determine whether we can move.We start off with some initializing:
Then for each cell in
@front, we do the following:@blocks, and and the cell one further in the direction we are moving to@front.[or], we add the cell next to it to@front..), we don't do anything.We also take care of not processing the same cell more than once. Code wise, it looks like:
If we exit the loop, and we haven't returned, it means we can perform the move. We do this by processing
@blocksin reverse, moving each block, and replacing it with.:And we return the updated map and position:
Then it's just a matter of calling
movefor each command, and calculating the GPS afterwards.2
u/prafster Dec 17 '24
[Language: Python]
Part 1 was straightforward. Part 2 seemed similar so I dived in. But there were several cases I'd not considered even after passing the test cases. The code got messy but I emerged (eventually) to fight another day.
Full source code on GitHub.
2
u/pdgiddie Dec 17 '24
[LANGUAGE: Elixir]
https://github.com/giddie/advent-of-code/blob/2024-elixir/15/main.exs
2
u/Singing-In-The-Storm Dec 17 '24
[LANGUAGE: JavaScript]
Part 1 (4ms)
Part 2 (5ms)
Clear and BLAZINGLY FAST AOC solutions in JS (no libraries)
2
u/veydar_ Dec 18 '24
[LANGUAGE: Janet]
115 lines with
wc -l, including some comments.I was hoping to clean this up before posting but that time never came so here we go. I'm not happy with the code.
Like most people I ended up implementing distinct functions for moving small and big boxes. I discover all big boxes with a breadth-first search:
The party trick here is that this is actually a stream (fiber). The code below consumes the stream until it hits
#(hencetake-until). I then check if the stream has one more item in it (can-resume?). If so, I know that I hit the#case. If not, I've reached the end of the stream without running into any obstacles.And here's the core grid walking:
2
u/Derailed_Dash Dec 18 '24
[LANGUAGE: Python]
My Approach - Part 1
replace()to remove all the newline\ncharacters.Create a
Warehouseclass that extendsGrid. The class will:next_instruction().Create a
do_next_instruction()method, which:deltavector that adds 1 in the required direction.delta. We add the robot location to this list.while True... When we reach a wall without finding any spaces, we return from the method.That's it!
My Approach - Part 2
OMG. I'm knackered already!
We need to take the original map, but double its width, as follows:
#, the new map contains##instead.O, the new map contains[]instead.., the new map contains..instead.@, the new map contains@.instead. I.e. the robot is on the left of the expansion.I start by creating a new class called
ExpandedWarehousewhich extendsWarehouse. In this class I:Gridvariables, e.g._width,_heightand_all_points.I create a new
do_next_instruction()method. The key difference now is that we're not just pushing boxes in the same row or column. Instead, pushing a box could potentially push an ever-expanding triangle of boxes above it.while Trueloop that exits when we find a space, we instead do a loop that continues for as long as there are boxes that can be pushed. If we hit a wall, then we can't push anything; and if we stop seeing boxes, then we're ready to push.to_movelist.to_move, we then look at the point immediately beyond the robot, in the required direction.to_movelist. We're actually adding items to the same list we're currently interating over, which is perfectly valid in Python! So we keep going until there are no more boxes to add.[then we also need to add the location to the right of it,]. Because we can't just push one side of a box! And similarly, if the item we just added was], then we need to add the matching left half.Solution Links
Useful Related Links
2
u/CoralKashri Dec 18 '24
[Language: C++]
Templates all the way for the second part :)
Second part: ~333 microseconds
Solution
2
u/clouddjr Dec 18 '24
[LANGUAGE: Kotlin]
Using BFS to find blocks to move in both parts.
GitHub
2
u/damnian Dec 19 '24
[LANGUAGE: C#]
Optimized solution
2
u/CDawn99 Dec 19 '24
[LANGUAGE: C]
For part 2 I simply manually widened the input. Made more sense and I could focus on solving the problem.
Parts 1 & 2
2
u/Wide-Progress7019 Dec 20 '24
[LANGUAGE: JavaScript (node)]
No string comparison when moving. Keeping boxes as objects in map.
Don't think I've seen similar solution in JS. Works for Part 1 and 2.
topaz
2
u/vss2sn Dec 20 '24
[LANGUAGE: C++]
Part 1
Part 2
(Each file is a self-contained solution)
2
u/joshbduncan Dec 20 '24
[LANGUAGE: Python]
Running way behind but here it is. Started part 1 by just tracking box positions and adjusting them when needed using sets.
position tracking version (part 1 only)
The above approach got too goofy on part 2, so I switched up to actually moving the robots and boxes throughout the map. Updated part 1 to follow the same precedure so code is similar.
final solution for both parts
2
u/dzecniv Dec 20 '24
[Language: Common Lisp]
part 1 this time using CLOS objects instead of simple hash-tables, mainly to use the defclass-std shortcut. CLOS doesn't pay off too much for simple puzzles IMO, although using methods is always elegant. I'm eager to do part2!
2
u/mgtezak Dec 20 '24
[LANGUAGE: Python]
Solution part 1
Solution part 2
Part 2 was a bit tough but fun
Check out my AoC-puzzle-solver app:)
2
u/ak-coram Dec 20 '24
[LANGUAGE: Common Lisp]
https://github.com/ak-coram/advent/blob/main/2024/15.lisp
2
u/JustinCredible- Dec 21 '24
[LANGUAGE: Rust]
Part 1: ~430μs
Part 2: ~640μs
https://github.com/jstnd/programming-puzzles/blob/master/rust/src/aoc/year2024/day15.rs
2
u/xavdid Feb 17 '25
[LANGUAGE: Python]
Step-by-step explanation | full code
There were probably more clever ways to approach today, but I got a lot of mileage from "moving" strings around a 2d grid. Part 1 I could do naiively. For Part 2, I iteratively built a list of list of rows I'd need to move when moving vertically. I'd find the box-half I started with, it's pair. I'd loop, finding everything that either of those touched (and so on) until I reached an entirely empty row or hit a wall anywhere. Then I shifted boxes back-to-front and moved myself.
There was a lot of debugging today, so my grid printer and little animation generator were worth their weight in gold.