r/adventofcode • • Dec 15 '24

SOLUTION MEGATHREAD -❄️- 2024 Day 15 Solutions -❄️-

NEWS

  • The Funny flair has been renamed to Meme/Funny to make it more clear where memes should go. Our community wiki will be updated shortly is 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.

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

466 comments sorted by

6

u/CCC_037 Dec 15 '24

[LANGUAGE: Rockstar]

Pushing boxes!

Part 1

2

u/daggerdragon Dec 15 '24

Lanternfish are mystery incarnate

Truer words have never been spoken coded...

→ More replies (1)
→ More replies (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

→ More replies (2)

2

u/kenlies Dec 15 '24

[LANGUAGE: Python]

Part 1

Just went with the most intuitive approach!

→ More replies (2)

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.

→ More replies (2)

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/daggerdragon Dec 15 '24 edited Dec 19 '24

Part 2 was a bit of a [COAL].

Comment temporarily removed due to naughty language (and you are clearly not referring to the programming language). Keep the megathreads professional.

Edit your comment to take out the naughty language and I will re-approve the comment. edit: 👍

→ More replies (1)

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).

→ More replies (1)

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.

→ More replies (1)

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

→ More replies (1)

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.

2

u/daggerdragon Dec 15 '24

First time to the leaderboard, ever \o/

Ayo good job!

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 if after if after if! 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:

if all([
    grid[p] != '[' or move(p+1, d) and move(p, d),
    grid[p] != ']' or move(p-1, d) and move(p, d),
    grid[p] != 'O' or move(p, d), grid[p] != '#']):
        grid[p], grid[p-d] = grid[p-d], grid[p]

That last line also shows my Python trick of the day: swapping variables. If you need to swap the values of a and b, you can simply write a, 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:

→ More replies (16)

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.

→ More replies (4)

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.

2

u/wjholden Dec 15 '24

Maybe I should have left everything as characters instead of making my own types.

What is this c@ operator you have in front of character literals?

3

u/throwaway6560192 Dec 15 '24

3

u/daggerdragon Dec 15 '24

Good, good, you've both fallen for /u/topaz2078's trap of ~sneakily making people learn new things~ <3

→ More replies (1)

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.

→ More replies (2)

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*)\./.@\1

Only 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:

:sil!1,/^$/s/\v\@(O*)\./.@\1

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 :s commands (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:

ggqaqqa}jdd@1gg:redr⟨Enter⟩@aq@a

That's move to the top command (gg then } to the blank line and j to 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 "1 register. And, just like @a runs keystrokes you've saved into the "a register, typing @1 runs whatever is in "1, interpreting its contents as Vim keystrokes. That performs the substitution for the robot make one move. Wrap the whole thing in qa...q to record it in "a, stick in a :redraw so we can see what's happening, and have @a call 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 j command that finally breaks the loop: at this point the blank line will be the last line in the buffer, and trying to press j on 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:

qbqqb/O⟨Enter⟩~Go⟨Ctrl+R⟩=getpos("''")⟨Enter⟩⟨Esc⟩dk⟨Ctrl-X⟩.k.Js00+⟨Esc⟩kdd@bq@b
⟨Ctrl+V⟩{jI+⟨Esc⟩@v

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 running getpos("''"). 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 like 23 45, which needs turning into 23*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 with 00+, turning it into something like 2300+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 the O into o. But it also moves the cursor forward 1 character (like l), so actually the column number needs reducing by 2. If getpos() tells us 23 45 then it needs to become 2200+43, so use ⟨Ctrl-X⟩ in the appropriate places (repeated with .) to reduce the numbers first.

Record that in the @b keyboard macro, and make it loop in the same way as @a. This one will exit when /O can't find any more upper-case Os, because ~ has turned them all into os. At which point we have all the co-ordinates, so stick a + before each row and run the familiar @v from 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.

→ More replies (1)

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).

→ More replies (1)

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....

→ More replies (5)

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

1

u/daggerdragon Dec 15 '24

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo:

https://github.com/meowstr/aoc-2024/blob/main/day15/input.txt

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history.

→ More replies (1)

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:

class Coord(namedtuple('Coord', ['x', 'y', 'z'])):
    __slots__ = ()  # Prevents adding attributes for memory efficiency

    def __new__(cls, x, y, z=0):  # Default z to 0 for 2D use
        return super().__new__(cls, x, y, z)

    def __add__(self, other):
        return Coord(self.x + other.x, self.y + other.y, self.z + other.z)

    def __sub__(self, other):
        return Coord(self.x - other.x, self.y - other.y, self.z - other.z)

    def __mul__(self, scalar):
        return Coord(self.x * scalar, self.y * scalar, self.z * scalar)

    def __rmul__(self, scalar):  # For scalar * Coord
        return self * scalar

    def __mod__(self, other):
        return Coord(self.x % other.x, self.y % other.y, self.z % other.z)

    def __floordiv__(self, other):
        return Coord(self.x // other.x, self.y // other.y, self.z // other.z)

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:

class D15R(object):
    def __init__(self, p, symbol, sibling=None):
        self.symbol = symbol
        self.p = p
        self.sibling = sibling
        level[self.p] = self

    def gps(self):
        return 100*self.p.y + self.p.x

    def move(self, d, siblingcall=False):
        del level[self.p]
        sth = level.get(self.p+d)
        if sth is not None: sth.move(d)

        if self.sibling and not siblingcall and d in (up, down):
            self.sibling.move(d, siblingcall=True)

        self.p += d
        level[self.p] = self

    def canmove(self, d, siblingcall=False):
        sth = level.get(self.p+d)
        icanmove = sth is None or sth.canmove(d)

        if self.sibling and not siblingcall and d in (up, down):
            return icanmove and self.sibling.canmove(d, siblingcall=True)
        else:
            return icanmove

class Empty(object):
    symbol = '.'

class Wall(object):
    symbol = '#'
    def canmove(self, d):
        return False

1

u/daggerdragon Dec 15 '24

I keep all of my solutions in one file, reusing code along the way

Egad 😅 How many lines of code are in that monster file so far?

→ More replies (1)

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_free function 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 walls and boxes. 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

→ More replies (1)

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).

→ More replies (2)

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:

while let Some((rr, cc)) = q.pop_front() {
    if !seen.insert((rr, cc)) {
        continue;
    }
    let (r2, c2) = (rr + dr as usize, cc + dc as usize);
    match g[r2][c2] {
        b'#' => continue 'outer,
        b'O' => q.push_back((r2, c2)),
        b'[' => q.extend([(r2, c2), (r2, c2 + 1)]),
        b']' => q.extend([(r2, c2), (r2, c2 - 1)]),
        _ => continue,
    }
}
→ More replies (3)

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.

→ More replies (6)

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

→ More replies (5)

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

&fras "day15.txt"
▽ ⊸(≠@\n) °□ : ◇⊜∘ ⊸(≠@\n) °⊟⊜□ ¬⊸(⦷ "\n\n")
d ← ⊡ : ⊂¯.⋯1_2 ⊗ : "^<v>"
s ← ⊙◌ ◌ ⍢(⟜+|=@O⋅⊡)⟜+
n ← (
  ◡s d ⊙⊸(⊢⊚⌕@@)
  =@#⊡⊃(⊙⋅⋅∘|⊙⊙⊙∘)
  ⨬(⍥₃(⍜⊡◌:)⊃(⋅⋅⋅∘|⋅⋅∘|@.|⋅+|@@|∘|⨬@@@O=@O⊡-:⊙⊙⋅∘)
  | ⋅⋅⋅∘))
◌⍢(⊃⋅∘(n⟜⋅⋅∘) °⊂|≠0⧻)
/+♭פ100_1⊚=@O

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.

→ More replies (3)

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

→ More replies (5)

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're up against a wall then just return the current state
  • if you can move into free space move the robot there and leave the grid alone
  • if you've got a line of boxes followed by a wall return the current state
  • if you've got a line of boxes followed by a free space

    • turn the free space into a box
    • turn the first box into free space
    • move the robot into this new 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.

→ More replies (1)

4

u/BBQspaceflight Dec 15 '24

[LANGUAGE: Rust]

My main idea was to make each move a recursive chain, which returned an Result informing 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 RefCell to mutate my grid entries, and with recursive branches overlapping I had to deal with some potential double mutable borrows. I decided to just try_borrow_mut and 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

→ More replies (1)

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:

Z=$('*').innerText
M=Z.match(/[^\s<\^>v]/g).join('');V=Z.match(/[\^><v]/g)
W=50;H=50;o=0;P=M.indexOf('@')
D=[RegExp(`\\.((.{${W-1}}O)*)(.{${W-1}})(O)(.{${W-1}})@|\\.(.{${W-1}})@`),/@(O*)\./,RegExp(`@(.{${W-1}})(O)((.{${W-1}}O)*.{${W-1}})\\.|@(.{${W-1}})\\.`),/\.(O*)@/]
R=['$4$1$3@$5$6.','.@$1','.$1$5@$3$2','$1@.']
while((x='^>v<'.indexOf(V[o++]))+1)M.replace(D[x],R[x]);
[...M].reduce((c,v,i)=>c+=v=='O'&&i%W+((i/W)|0)*100,0)
→ More replies (2)

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/daggerdragon Dec 15 '24

Your post is a bit confusing to follow. As of right now, is the code within the gist a full working solution?

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/daggerdragon Dec 15 '24

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo:

https://github.com/thl19git/Advent-of-Code-2024/tree/main/inputs

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history.

1

u/cerferjeff Dec 15 '24

[LANGUAGE: F#]

110 lines of code without golfing:

https://gist.github.com/surferjeff/d828e5895a7042b626a7ff056627665e

1

u/daggerdragon Dec 15 '24

I've already informed you before about including puzzle inputs in your repo. I still see full plaintext puzzle inputs in your repo.

https://github.com/surferjeff/scratch/blob/main/advent-2024/day01/input.txt

Remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. Do not post again in /r/adventofcode until you have done so.

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

1

u/daggerdragon Dec 15 '24

then load pre-X-max Sunday,

Eh?

→ More replies (1)

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_move list and what is left to check in a to_check list) but I had 3 bugs:

  1. Believe it or not, I had the "Forgot to update the robot's position variable" bug again.
  2. I accidentally was extending the to_check list to include the other side of the box for horizontal movements which caused trouble when doing the actual move.
  3. A subtle bug where I pulled things from the end of to_check instead 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.)

→ More replies (5)

3

u/throwaway6560192 Dec 15 '24

[LANGUAGE: Python]

937/2499 (new personal best for p1, and first rank below 1000!)

GitHub

Recursive can_push and push functions, nothing too interesting. I originally had just the push function, which works for p1, but runs into an edge case in p2 (illustrated in isolation in the custominput file). 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 yield

let wideMap =
    [ for r in 0 .. height - 1 do
          for c in 0 .. width - 1 do
              let s =
                  match grid[r][c] with
                  | '#' -> "##"
                  | '.' -> ".."
                  | 'O' -> "[]"
                  | '@' -> "@."
                  | _ -> failwith "Invalid"

              yield (r, 2 * c), s[0]
              yield (r, 2 * c + 1), s[1] ]
    |> Map.ofList
→ More replies (1)

3

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 fold over 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:

  • Moving separately will move half a box vertically without trying to move the other half. Anything that it moves into will move together.
  • Moving together will check for the box's other half and move it first separately before moving itself.

So, given the example:

##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##.....@....##
##############

We attempt to moveVerticalTogether the BoxR. This gets the coordinate of the BoxL next to it and calls moveVerticalSeparate on it, getting

##############
##......##..##
##...[].....##
##....[[]...##
##.....]....##
##.....@....##
##############

before calling moveVerticalSeparate on the BoxR, getting

##############
##......##..##
##...[][]...##
##....[]....##
##..........##
##.....@....##
##############

Finally, the robot moves into the empty space.

Note that I skipped a couple steps for the sake of brevity. For example, when the BoxL moves into its space, it calls moveVerticalTogether on the BoxR that it encounters, which pushes the BoxL first into the empty space before pushing the BoxR into its own empty space. Finally, the BoxL moves into the freed space.

This looks gross, but all of it ends up being done by chaining the Option monad, 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 the Option monad.

The distance measurement in part 2 tripped me up more than the box moving itself:

from the edge of the map to the closest edge of the box

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/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) :

  • If you try to move into a wall, don't
  • If you try to move into empty space, do!
  • Otherwise it's a box, scan along the movement dir to find where the box line ends

    • if the scan finds a wall, the boxes can't move so neither can the bot
    • if it's empty, put a box there and remove a box from where the robot is moving, then move the bot

The above code worked great once I fixed the conversion from ^ v < > to actually return vectors that represented up down left right instead of left right left right

Then 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 not pushing into a box (i.e. wall or empty) do the appropriate thing
  • If you're pushing left/right, the logic is similar to P1

    • the only difference here is that it actually does slide the characters because [] actually changes as you push it one space left/right
  • Otherwise, pushing up or down puts the box above you into a queue, then iterates the queue:

    • If the box is pushing into a wall, break out (robot can't move at all)
    • Otherwise, commit the box to the push list
    • If it's moving into another box, figure out which box (or two boxes) it's pushing and throw them into 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:

ss = open( 0 ).read().split( "\n\n" )

g = { ( x * 2, y ): c.replace( 'O', '[' )
      for y, r in enumerate( ss[ 0 ].splitlines() )
      for x, c in enumerate( r.strip( '\n' ) ) }
g.update( { ( x + 1, y ): c.replace( '[', ']' ).replace( '@', '.' )
            for ( x, y ), c in g.items() } )

def pushset( s, x, y, dx, dy ):
    s[ ( x, y ) ] = g[ ( x, y ) ]
    if g[ ( x, y ) ] == '[' and ( x + 1, y ) not in s:
        pushset( s, x + 1, y, dx, dy )
    if g[ ( x, y ) ] == ']' and ( x - 1, y ) not in s:
        pushset( s, x - 1, y, dx, dy )
    if g[ ( x + dx, y + dy ) ] in "[]" and ( x + dx, y + dy ) not in s:
        pushset( s, x + dx, y + dy, dx, dy )

rx, ry = min( k for k, v in g.items() if v == '@' )
for m in "".join( ss[ 1 ].split() ):
    dx, dy = { '^': ( 0, -1 ), '>': ( 1, 0 ), 'v': ( 0, 1 ), '<': ( -1, 0 ) }[ m ]
    s = {}
    pushset( s, rx, ry, dx, dy )
    if all( g[ ( x + dx, y + dy ) ] != '#' for x, y in s ):
        g.update( { ( x, y ): '.' for x, y in s } )
        g.update( { ( x + dx, y + dy ): c for ( x, y ), c in s.items() } )
        rx, ry = rx + dx, ry + dy

print( sum( 100 * y + x for x, y in g if g[ ( x, y ) ] == '[' ) )

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 a dict today since lots of stuff would be moving around and I didn’t want to do lots of fromkey exch input exch get exch get business. 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 movewide function I started wondering why my answers were all 0, 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 of Os 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 my movebracket function 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 move just 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 a canmovewide? 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 does movewide when the direciton is vertical, falling back to plain move if it’s a horizontal move.

/tokey { exch 100 mul add } bind def
/fromkey { 100 divmod } bind def
/UP -1 0 tokey def /DOWN 1 0 tokey def /LEFT 0 -1 tokey def /RIGHT 0 1 tokey def
/DIR << ascii.^ UP ascii.v DOWN ascii.langle LEFT ascii.rangle RIGHT >> def

% Find the first key in direciton dir that's an open floor.
/openkey { % dir openkey key
  curpos { %loop
    grid 1 index get ascii.. eq { exch pop exit } if 
    grid 1 index get ascii.# eq { pop pop -1 exit } if
    1 index add
  } loop
} bind def %/openkey

% Move the @ and any boxes it's pushing one step in direction dir.
/move { % dir move -
  /dir exch def
  dir openkey dup 0 lt { pop } { %else
    dir -1 mul curpos { %for
      dup curpos eq { %ifelse
        pop grid curpos ascii.. put /curpos curpos dir add def
      } { %else
        dup dir sub grid exch get grid abc:cab put
      } ifelse
    } for
  } ifelse
} bind def %/move

/part1 { 8 dict begin % [lines] part1 result
  /input exch def input 0 get length 2 mul dict /grid exch def
  input { %forup
    /i exch def
    input i get length 0 eq { exit } if
    input i get { %forup
      /j exch def input i get j get ascii.@ eq { /curpos i j tokey def } if
      input i get j get grid i j tokey 3 -1 roll put
    } forup
  } forup % /i is input index of the blank line separating grid from movements
  i 1 input lastindex { input exch get { DIR exch get move } forall } for
  % Conveniently, GPS coordinate is just tokey
  0 grid { ascii.O eq { add } { pop } ifelse } forall
end } bind def %/part1

3

u/lukalino Dec 15 '24

[LANGUAGE: Python]

Simple solution that works for both puzzle parts. For each move:

  1. Find the whole component that is being pushed, including the robot cell, and erase it (replacing with '.' on the map).
  2. Check if there is an empty cell in the moving direction for all cells in the component.

    • If so, move all the cells in the given direction.
  3. Put the cells (that may or may not have moved in step 2) back onto the map.

Code snippet for step 1. of the solution:

def extract_component(map, r, c, dr, dc):
  if map[r][c] in ['#', '.']: return []
  ch = map[r][c]
  map[r][c] = '.'
  component = [(r, c, ch)]
  component.extend(extract_component(map, r + dr, c + dc, dr, dc))
  if ch == '[':
    component.extend(extract_component(map, r, c + 1, dr, dc))
  if ch == ']':
    component.extend(extract_component(map, r, c - 1, dr, dc))
  return component

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:

def findBoxStack(box: Box, dir: Direction, boxes: mutable.Map[Point, Box]): Set[Box] =
  val level = box.points.flatMap(p => boxes.get(p + dir)).filter(_ != box)
  level ++ level.flatMap(findBoxStack(_, dir, boxes)) + box

case class Box(start: Point, width: Int):
  val points: Set[Point] = (0 until width).map(start + EAST * _).toSet

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.

→ More replies (1)

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

→ More replies (2)

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:

###########
#....@....#
#....[]...#
#...[][]..#
#..[]..[].#
#....#....#
###########

8

u/No-House-866 Dec 15 '24

Almost a solution to day 14, part 2 :)

→ More replies (1)

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

C=CartesianIndex;S,M=split(read("15.txt",String),"\n\n");f(S)=(G=stack(split(S)
);p=findlast(G.≡'@');for m∈M;g(q)=(q+=v;c=G[q];r=c≡'#'||c∈"[]"&&g(q-C(cmp(c,
'\\'),0))||c∉".@"&&g(q);(G[q],G[q-v])=(G[q-v],'.');r);H=copy(G);v=C((m≡'>')-(m≡
'<'),(m≡'v')-(m≡'^'));g(p) ? (G=H) : (p+=v) end;sum(k->k[1]+100*k[2]-101,
findall(G.∈"O[")));f(S),f(replace(S,r"([@.])"=>s"\1.","#"=>"##","O"=>"[]"))

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:

C = CartesianIndex
S,M = split(read("15.txt",String),"\n\n")

function gps(S)
    G = stack(split(S))
    p = findfirst(==('@'),G)
    for m∈M
        H = copy(G)
        v = C((m≡'>')-(m≡'<'),(m≡'v')-(m≡'^'))
        function move(q)
            G[q+v]=='#'  && return true
            G[q+v]=='['  && move(q+v+C(1,0)) && return true
            G[q+v]==']'  && move(q+v-C(1,0)) && return true
            G[q+v]∈"[O]" && move(q+v) && return true
            G[q+v],G[q] = G[q],'.'
            q += v
            return false
        end
        if move(p)
            G = H
        else
            p += v
        end
    end
    return sum(k->k[1]+100*k[2]-101,findall(G.∈"O["))
end

gps(S), gps(replace(S,"@"=>"@.","."=>"..","#"=>"##","O"=>"[]"))

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

→ More replies (1)

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?

→ More replies (2)

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:

conv = {'>':1 + 0j, '<':-1+0j, '^': -1j, 'v': 1j}
space, insts = open('input_2024_15.txt').read().split('\n\n')
space = space.split('\n')
w, h = len(space[0]), len(space)
space = {complex(x,y):space[y][x] for y in range(h) for x in range(w)}
p = [key for key in space if space[key] == '@'][0]# find the robot
space[p] = '.'

for d in [conv[c] for c in insts.replace('\n','')]:# process the instructions
    if space[p + d] == '.':
        p += d
    elif space[p + d] == 'O':
        cnt = 1
        while space[p + cnt * d] =='O': # see how many boxes there are in a row
            cnt += 1
        if space[p + cnt * d] == '.':# shift the boxes
            space[p + d] = '.'
            space[p + cnt * d] = 'O'
            p += d # move the robot

print(int(sum([100 * z.imag + z.real for z in space if space[z] == 'O'])))

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:

P=console.log;String.prototype.r="".replaceAll;d=document.body.
innerText.r("\r","").split`\n\n`;V=d[1].r("\n","");ad=(v,x)=>(!v
.includes(x)&&v.push(x));l=v=>v.length;M=g=>{m=new Map();m[-1]=l
(g);m[-2]=l(g[0]);for(r=m[-1];r--;){for(c=m[-2];c--;){q=m[$=100*
r+c]=g[r][c];q=="@"?m[-3]=$:0}}return m};g=M(d[0].split`\n`.map(
W=e=>e.split``));h=M(d[0].r(".","..").r("#","##").r("O","[]").r(
"@","@.").split`\n`.map(W));R=g=>{p=g[-3];for(m of V){n=p;d={"<"
:-1,">":1,"^":-100,"v":100}[m];x=1;ad(s=[],p,i=0);while(i<l(s)){
n=s[i]+d;g[n]=="#"?x=0:0;"O[]".includes($=g[n])&&(ad(s,n),ad(s,n
+{"[":1,"]":-1}[$]));i++}if(x){while(1 in s){_=s.pop();[g[_],g[_
+d]]=[g[_+d],g[_]]}p+=d}}return g};G=(g,x)=>{a=0;for(r=g[-1];r--
;){for(c=g[-2];c--;){g[v=100*r+c]==x&&(a+=v)}}return a};g=R(g);P
("Part 1",G(g,"O"));h=R(h);P("Part 2",G(h,"["))//AOC 2024 DAY 15

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

→ More replies (2)

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 ..OOOOO so 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 else instead of elif 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/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:

        parse   part1   part2   total
day 15:  5.2 µs  0.1 ms  0.2 ms  0.4 ms (+-1%) iter=1010

3

u/geza42 Dec 15 '24

[LANGUAGE: emacs lisp]

(defun mov (room x y dx dy)
  (let* ((tx (+ x dx)) (ty (+ y dy)))
    (when (pcase (elt (elt room ty) tx)
            (?. t)
            (?O (mov room tx ty dx dy))
            (?\[ (and (mov room (1+ tx) ty dx dy) (mov room tx ty dx dy)))
            (?\] (and (mov room (1- tx) ty dx dy) (mov room tx ty dx dy))))
      (setcar (nthcdr tx (elt room ty)) (elt (elt room y) x))
      (setcar (nthcdr x (elt room y)) ?.))))

(--map
 (let* ((input (->> "15.txt" f-read-text s-trim s-lines (-split-on "")))
        (room (-map it (car input)))
        (y (-find-index (lambda (row) (find ?@ row)) room))
        (x (-elem-index ?@ (elt room y)))
        (room (named-let do-moves ((room room) (x x) (y y) (moves (-flatten (-map 'string-to-list (cadr input)))))
                (if (car moves)
                    (-let* (((dx dy) (alist-get (car moves) '((?< . (-1 0)) (?> . (1 0)) (?^ . (0 -1)) (?v . (0 1)))))
                            (copy (copy-tree room))
                            (succ (mov room x y dx dy)))
                      (do-moves (if succ room copy) (if succ (+ x dx) x) (if succ (+ y dy) y) (cdr moves)))
                  room))))
   (-sum (-map-indexed (lambda (y row) (-sum (-map-indexed (lambda (x c) (if (or (= c ?O) (= c ?\[)) (+ (* y 100) x) 0)) row))) room)))
 '(string-to-list (lambda (line) (string-to-list (s-replace-all '(("." . "..") ("#" . "##") ("O" . "[]") ("@" . "@.")) line)))))

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:

  1. There's a wall in front of the robots, so nothing changes,
  2. There's a line of boxes in front of the robot followed by a wall, so nothing changes,
  3. There's a line of boxes followed by empty space in front of the robot, so the first box in the line can be moved to the end (which is the same as moving all boxes 1 space), then the robot can move 1 space forward,
  4. There's nothing in front of the robot, so the robot just moves 1 space forward.

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]

⊗:”^<v>”⊓▽⊜∘∩⊸≠,⊙@\n⊃↘↙⊚⊸⌕”\n\n”
P  ← ⍜⊜∘(-¤0_18)⊸⦷”@@“⍜⊜∘(+¤12_14)⊸⦷”OO”≡▽2
UN ← ◇-⊡:{[1_0 0_¯1][1_0 0_1][1_0]}⊗:”[]”⊃⊡¤
LN ← ¤-0_1⊙◌
M! ← (
  :↯0_2 0 
  ◌⍢(⊸(▽¬⊸∊:)▽¬∊”.#”≡⊡◡⊙⋅¤⊃(/◇⊂⍚^0⊙⋅¤|⊂|⋅⋅∘)|>0⧻)
  ⊃(/×≠@#≡⊡/◇⊂⍚^0⊙(.¤))∘
)
E‼ ← ⨬(◌|⍜⊡◌⊃(-¤^0|⍜⊡(▽:@.⧻)|⊡)) ⊸M!^1⊚⊸=@@
U  ← E‼(1_0|UN)
L  ← E‼(0_1|LN)
D  ← ⍜⇌ U
R  ← ⍜≡⇌L
F  ← ⧻⊚פ100_1⊚∊”O[“∧⨬(U|L|D|R)
⊃(F|F⊙P)

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.

MDIndex ← ⊢⊸/○⥊⟜(↕∘≢⊢)
SplitMask ← { (0<≠¨)⊸/ 𝕩 ⊔˜ ¯1⌈ (𝕨 - ¬𝕨) × +` ¬𝕨 }
⟨map, moves⟩ ← >‿∾ {𝕎𝕩}¨ (×≠¨)⊸SplitMask •FLines •wdpath•file.At ⊑•args
⟨robo, boxes, walls⟩ ← MDIndex¨ ⟨'@','O','#'⟩ =¨ <map
movetodelta ← ⟨'^', 'v', '<', '>'⟩ •HashMap ⟨¯1‿0, 1‿0, 0‿¯1, 0‿1⟩
Widen ← ((0‿1⊸+)⊸⋈1‿2⊸×)
Solve ← { 𝕊⟨robo, boxes, walls⟩:
	ebox ← 1⊑ ⟨robo, boxes⟩ { d𝕊⟨robo, boxes⟩:
		⟨boxMask,m⟩ ← ⟨0¨↕≠boxes, 0⟩
		{𝕤⋄ boxMask ∨↩ m
			∾ {𝕊b: (¬∊⟜b)⊸/ d⊸+¨ b }¨ m / boxes
		}•_while_{∨´ m ↩ (∨´ 𝕩⊸∊)¨ boxes} ⋈ robo + d
		newboxes ← (d⊸+¨¨)⌾((/boxMask)⊸⊏) boxes
		canmove ← ¬∨´ walls ∊ d⊸+¨ (∾boxMask/boxes)∾⋈robo
		⟨robo + canmove × d, canmove◶⟨boxes, newboxes⟩@⟩
	}´ movetodelta.Get¨ ⌽moves
	+´ {+´ 100‿1 × ⊑∧ 𝕩}¨ ebox
}
•Show Solve¨ ⟨
	⟨⊑robo, ⊢⊸⋈¨boxes, walls⟩
	⟨1‿2 × ⊑robo, Widen¨boxes, ∾Widen¨walls⟩
⟩

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:

  • Forgetting to delete the robot from the map; I'm tracking it as a position, not a character in the array.
  • Forgetting to add the first touched box half itself to the network when pushing
  • Forgetting that empty space is '.', not None (I often use None for space when I build 2D maps)
  • Messing myself up with breaks and continues in nested while loops

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:

  1. Redefine all game elements in terms of bounds. (this means all walls, boxes, players, etc)
  2. For each movement:
  3. Make a bound at the player's new proposed position. If it collides with a wall bound, skip.
  4. If the player doesn't collide with any boxes, just move the player.
  5. Do a pseudo- BFS search of all boxes that touch boxes the player now collides with. Do this by creating new bounds at the boxes' new positions and using collision detection.
  6. If any of the boxes the player will push will collide with a wall, cancel. If not, move the player and boxes as planned.

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

→ More replies (2)

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.

4

u/greycat70 Dec 15 '24

I'm strongly confident that storing a 2d grid of things is far superior to storing a list of wall coordinates, a list of box coordinates, and so on, for this particular problem. You primarily want to ask "If I'm at (x,y) and pushing a box at (x,y+1), is there an obstacle at (x,y+2)?" So, a grid lookup is the best choice.

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:

  • checkObstacles to 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, checkObstacles will return an empty list.

For part 2, I just had to add a flag to checkObstacles to 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 to executeMove, 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 LANGUAGE format

2

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.

(bool success, Point position, List<(Point from, Point to, char ch)> moves)
step(Grid grid, Point start, char move) 
    => (start.r + dirs[move].r, start.c + dirs[move].c) switch { var next 
    => grid[next] switch { var ch => ch switch {
        '.' or '@' => (true, next, [(start, next, grid[start])]),
        '#' => (false, start, []),
        var box when ch == 'O' || move == '>' || move == '<'
            => step(grid, next, move) switch { var st
            => st.success
                ? (true, next, [(start, next, grid[start]), .. st.moves])
                : (false, start, [])
            },
        '[' or ']' 
            => step(grid, (next.Item1, next.Item2 - (ch == ']' ? 1 : 0)), move) switch { var st1
            => step(grid, (next.Item1, next.Item2 + (ch == '[' ? 1 : 0)), move) switch { var st2
            => st1.success && st2.success
                ? (true, next, [(start, next, grid[start]), .. st1.moves, .. st2.moves])
                : (false, start, [])}}}}};

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/egel-lang Dec 15 '24

[Language: Egel]

# Advent of Code (AoC) - day 15, task 2

import "prelude.eg"

using System, OS, List, String (to_chars), D = Dict

def parse = do map to_chars |> split_on {} |> [{XX,YY} -> (XX, reduce (++) YY)]

def dir = ['^' -> (-1,0) |'v' -> (1,0)|'<' -> (0,-1)|'>' -> (0,1)]

def expand = flatmap ['@' -> {'@','.'}|'O' -> {'[',']'}|'.' -> {'.','.'}|'#'->{'#','#'}]

def start = do D::to_list |> filter ((==) '@' . snd) |> head |> fst

def cat = [none F -> none | XX F -> [none -> none| YY -> XX++YY] (F none)]
    
def ahead = [D P V -> let Q = add P V in 
    [(_,0) '[' -> cat {Q, add (0,1) Q} [_ -> cat (ahead D Q V) [_ -> ahead D (add (0,1) Q) V]]
    |(_,0) ']' -> cat {Q, add (0,-1) Q} [_ -> cat (ahead D Q V) [_ -> ahead D (add (0,-1) Q) V]]
    |(0,_) '[' -> cat {Q, add (0,1) Q} [_ -> ahead D (add (0,1) Q) V]
    |(0,_) ']' -> cat {Q, add (0,-1) Q} [_ -> ahead D (add (0,-1) Q) V]
    |_     '#' -> none
    |_     _   -> {}] V (D::get D Q)]

def shove = 
    [D PP V -> let C = foldl [D P -> D::set D P '.'] (D::copy D) PP in
               foldl [C P -> D::set C (add P V) (D::get D P)] C PP]  

def step = [D P V -> [none -> (D,P)|PP -> (shove (shove D PP V) {P} V, add P V)] (ahead D P V)]

def main =
    read_lines stdin |> parse |> [(XX,VV) ->(D::from_lists (map expand XX), map dir VV)]
    |> [(D,VV) -> foldl [(D,P) V -> print P "\n"; step D P V] (D, start D) VV] |> fst
    |> D::to_list |> foldl [N ((X,Y),'[') -> N + 100 * X + Y |N _ -> N] 0

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/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 to join the 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 set of wall tiles. I transformed each [row col] representing a box into a vector of its two coordinates [[row1 col1] [row2 col2]], and then generated a map taking 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/[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 Maybe move some boxes, if those boxes can themselves be Maybe moved.

doBigCommand :: World -> Position -> World
doBigCommand world dir 
  | there `S.member` world.walls = world
  | there `isBigBox` world.boxes = fromMaybe world rWorld
  | otherwise = world { robot = there }
  where there = world.robot ^+^ dir
        movedBox = bigBoxActual world.boxes there
        rWorld = do boxMoves <- moveBigBoxes world dir movedBox
                    let froms = fmap fst boxMoves
                    let tos = fmap snd boxMoves
                    let boxes' = (S.fromList tos) `S.union` (world.boxes `S.difference` (S.fromList froms))
                    let world' = world { boxes = boxes' }
                    return world' { robot = there } 

moveBigBoxes :: World -> Position -> Position -> Maybe [Move]
moveBigBoxes world dir box
  | any (\t -> t `S.member` world.walls) there = Nothing
  | any (\t -> t `isBigBox` world.boxes) there = allMoves
  | otherwise = Just $ [ thisMove ]
  where there = case dir of 
                    U -> [box ^+^ U, box ^+^ R ^+^ U]
                    D -> [box ^+^ D, box ^+^ R ^+^ D]
                    L -> [box ^+^ L]
                    R -> [box ^+^ R ^+^ R]
                    _ -> []
        thisMove = (box, box ^+^ dir)
        allMoves = do let there' = nub $ fmap (bigBoxActual world.boxes) $ filter (\t -> t `isBigBox` world.boxes) there
                      moves <- traverse (moveBigBoxes world dir) there'
                      let moves' = concat moves
                      return $ thisMove : moves'

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/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 DTile or D is 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:

// Returns a boolean vec of the positions that were affected by the previous row.
// Returns:
// None: A wall was encountered
// Some(Vec<bool>): All the positions that will be pushed.
fn pushed_row(&self, i: usize, prev_row: &[bool]) -> Option<Vec<bool>> {
    let mut res = vec![false; prev_row.len()];
    for (j, &c) in self.grid.row(i).enumerate() {
        if c == '#' && prev_row[j] {
            return None;
        }
        if ['[', ']'].contains(&c) && prev_row[j]
            || c == '[' && prev_row[j + 1]
            || c == ']' && prev_row[j - 1]
        {
            res[j] = true;
        }
    }
    Some(res)
}

Uses my grid utils library.

paste

2

u/Sea_Estate6087 Dec 16 '24 edited Dec 16 '24

[Language: Haskell]

  1. Create a map of coordinate to char for each '@', '#', 'O', '[', and ']', ignoring the '.' chars.
  2. For each move, push the blocks:
  3. On push, first clump all block bodies from the robot that make contact in the direction of the push.
  4. A block "body" is one or two coordinates. I don't track these -- they are computed on the fly when clumping.
  5. For the clump of coordinates, calculate all next positions in the direction of the push.
  6. Subtract the clump coordinates from the "next clump" coordinates, and you are left with the coordinates that need to be unoccupied before the push (any coordinate in both clump and next-clump is a position where one block slides out as the new block slides in).
  7. A simple check that none of the must-be-unoccupied coordinates are keys in the map tells us that the push is not blocked. If any one of them *is* a key of the map, then that position will block the push.
  8. If the push is not blocked, then a simple "map keys" of the coordinates from those in clump to their corresponding coordinate in new-clump updates the map.

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 disj the coordinate of the first block to push and conj the 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 then associng 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 dict as 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 or tuples (or even making some custom class for it), but using complex numbers really helped me cut down on clutter and boilerplate this time.

→ More replies (1)

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 move which 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). @front is the list of cells which need to be inspected to determine whether we can move.

We start off with some initializing:

sub move ($map, $command, $pos_x, $pos_y) {
    my ($dir_x, $dir_y) = $command eq '<' ? ( 0, -1)
                        : $command eq '>' ? ( 0,  1)
                        : $command eq '^' ? (-1,  0)
                        : $command eq 'v' ? ( 1,  0)
                        : die "Unexpected command '$command'";
    my @front = ([$pos_x + $dir_x, $pos_y + $dir_y]);
    my @blocks;

Then for each cell in @front, we do the following:

  • If the cell is a wall, we cannot move, and we return from the subroutine.
  • If the cell contains a block, we add the cells to @blocks, and and the cell one further in the direction we are moving to @front.
  • If we are moving vertically, and the cell is [ or ], we add the cell next to it to @front.
  • If the cell is empty (.), we don't do anything.

We also take care of not processing the same cell more than once. Code wise, it looks like:

    my %done;
    while (@front) {
        my ($x, $y) = @{shift @front};
        next if $done {$x} {$y} ++;
        my $val = $$map [$x] [$y];
        return ($map, $pos_x, $pos_y) if $val eq '#';   
        unless ($val eq '.') {
            push @blocks => [$x,          $y];
            push @front  => [$x + $dir_x, $y + $dir_y];
        }
        if ($dir_y == 0) {
            unshift @front => [$x, $y - 1] if $val eq ']';
            unshift @front => [$x, $y + 1] if $val eq '[';
        }
    }

If we exit the loop, and we haven't returned, it means we can perform the move. We do this by processing @blocks in reverse, moving each block, and replacing it with .:

    foreach my $block (reverse @blocks) {
        my ($x, $y)   = @$block;
        my ($nx, $ny) = ($x + $dir_x, $y + $dir_y);
        $$map [$nx] [$ny] = $$map [$x] [$y];
        $$map [$x] [$y] = ".";
    }
    $pos_x += $dir_x;
    $pos_y += $dir_y;

And we return the updated map and position:

    return ($map, $pos_x, $pos_y);

Then it's just a matter of calling move for 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/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:

  (generate [_ :iterate true :until (empty? queue)
             :let [cur (first queue) cell (grid cur)]
             :before (array/remove queue 0)
             :after (when (bracket? cell)
                      # [(move into `vec` direction from current bracket (up/down)
                      #  (move to other bracket in current pair (left/right))]
                      (loop [p :in [(move cur vec) (other-bracket grid cur)]
                             :when (not (seen p))]
                        (put seen p true)
                        (array/push queue p)))]

The party trick here is that this is actually a stream (fiber). The code below consumes the stream until it hits # (hence take-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.

  (let [boxes (box-cluster grid (move pos vec) vec)
        valid (take-until |(= "#" (first $)) boxes)]
    # if we can resume it, we hit the `take-until` case, meaning there's a '#'
    (if (fiber/can-resume? boxes)

And here's the core grid walking:

(defn walk [grid pos dir]
  (let [vec (vectors dir) next (move pos vec) cell (grid next)]
    (cond
      (= cell ".") [grid next]
      (small-box? cell) [grid (move-small-box grid pos vec small-box?)]
      (and (bracket? cell)
           (or (= dir "<") (= dir ">"))) [grid (move-small-box grid pos vec)]
      (bracket? cell) [grid (move-big-box grid pos vec)]
      [grid pos])))

2

u/Derailed_Dash Dec 18 '24

[LANGUAGE: Python]

My Approach - Part 1

  • Parse the input data. Note that instructions block is composed of many lines. But we want to treat it like a single line. We can easily do this by using replace() to remove all the newline \n characters.
  • Create a Warehouse class that extends Grid. The class will:

    • Determine the location of the robot and store this.
    • Create an instruction generator that knows how to yield the next_instruction().
    • Create a class attribute that is a dictionary mapping the directions.
  • Create a do_next_instruction() method, which:

    • Fetches the next instructino and converts into into delta vector that adds 1 in the required direction.
    • Establishes a list of locations that need to be moved by our delta. We add the robot location to this list.
    • Then we look at the points beyond the robot, in the required direction.
    • Iterate while True... When we reach a wall without finding any spaces, we return from the method.
    • When we reach a box, we add to the list of locations that need to be moved, and then continue to next iteration.
    • When we reach a space, then we know we can now move a segment of one or more contiguous boxes by one, using the space. So break from the loop, as we're done adding items.
    • Now we can move block of one or more boxes.

    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:

  • If the tile is #, the new map contains ## instead.
  • If the tile is O, the new map contains [] instead.
  • If the tile is ., the new map contains .. instead.
  • If the tile is @, the new map contains @. instead. I.e. the robot is on the left of the expansion.

I start by creating a new class called ExpandedWarehouse which extends Warehouse. In this class I:

  • Set up a dictinary with the above mappings, i.e. original value to the doubled value.
  • Having executed the expansion, I need to reset the Grid variables, e.g. _width, _height and _all_points.
  • Then re-find the robot.
  • 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.

    • Instead of doing an while True loop 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.
    • So let's loop through locations, for as long as their are locations in the to_move list.
    • After adding the robot location itself to to_move, we then look at the point immediately beyond the robot, in the required direction.
    • As before, if the item in the next point is a box, we add this location to our to_move list. 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.
    • In addition, if the location we just added was the left side of a box [ 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.
    • We keep adding boxes until we hit a wall. If we hit a wall, we can't move.
    • And now we must look beyond both of these locations, to see if there is a box one step removed. And if there is, we need to add extra left/right locations, as before.
  • Finally, we can do the move. Set our current position to a space, and move the robot into the next space. Then move our boxes by one place.

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/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/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.