Day 15: Warehouse Woes
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Uiua
Put this one off for a bit and Iβll put off part two for even longer because I donβt want to deal with any pyramid-shapes of boxes at the moment.
The code for part one feels too long but it works and runs <2s so Iβm happy with it for now ^^
Run with example input here
Code
I decided to split the movement instructions lines further for aesthetic reasons when opening it in the online uiua pad since newlines are thrown out anyways.
$ ##########
$ #..O..O.O#
$ #......O.#
$ #.OO..O.O#
$ #..O@..O.#
$ #O#..O...#
$ #O..O..O.#
$ #.OO.O.OO#
$ #....O...#
$ ##########
$
$ <vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><
$ <><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
$ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<
$ >><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
$ ><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v
$ ^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
$ <<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^
$ <vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
$ ^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>
$ >^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
$ ^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><
$ <<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
$ >^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv
$ <<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
$ <><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><
$ <><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
$ ^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^
$ >vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
$ v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v>
$ <^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^
Pos β :Β°ββββΈβ@@
Move β (
βΈβ@.
β£(+ββ€.β‘(β β⧻)
βββ£(β¬@.β»βββ€.=β(⧻|β@#).)β
)β
β
)
PartOne β (
# &rs β &fo "input-15.txt"
ββ‘Β¬β¦·"\n\n".
β©Β°β‘Β°β
: β(β½β @\n.) βββ @\n.
ββββ"^>v<"
β’(ββββ’
β(β(⨬(β|β)βΏβ)
β(⨬(β(βββ‘)Move Pos
| β(ββββ‘)Move +βPos
)=ββΏβ)
⨬(β|β)βΏβ
)
| β 0⧻)
β
/+β‘/+Γ[100_1]ββ@O
)
PartTwo β (
""
)
&p "Day 15:"
&pf "Part 1: "
&p PartOne
&pf "Part 2: "
&p PartTwo
C
3h+ train ride back home from weekend trip but a little tired and not feeling it much. Finished part 1, saw that part 2 was fiddly programming, left it there.
Finally hacked together something before bed. The part 2 twist required rewriting the push function to be recursive but also a little care and debugging to get that right. Cleaned it up over lunch, happy enough with the solution now!
Code
#include "common.h"
#define GW 104
#define GH 52
struct world { char g[GH][GW]; int px,py; };
static int
can_clear(struct world *w, int x, int y, int dx, int dy)
{
assert(x>=0); assert(x<GW);
assert(y>=0); assert(y<GH);
assert((dx && !dy) || (dy && !dx));
return
(x+dx >= 0 || x+dx < GW) &&
(y+dy >= 0 || y+dy < GW) &&
(w->g[y][x] == '.' || (
w->g[y][x] != '#' && can_clear(w, x+dx,y+dy, dx,dy) &&
(!dy || w->g[y][x]!='[' || can_clear(w, x+1,y+dy, 0,dy)) &&
(!dy || w->g[y][x]!=']' || can_clear(w, x-1,y, 0,dy)) &&
(!dy || w->g[y][x]!=']' || can_clear(w, x-1,y+dy, 0,dy))));
}
/* check can_clear() first! */
static void
clear(struct world *w, int x, int y, int dx, int dy)
{
assert(x>=0); assert(x<GW); assert(x+dx>=0); assert(x+dx<GW);
assert(y>=0); assert(y<GH); assert(y+dy>=0); assert(y+dy<GH);
if (w->g[y][x] == '.')
return;
if (dy && w->g[y][x] == ']')
{ clear(w, x-1,y, dx,dy); return; }
if (dy && w->g[y][x] == '[') {
clear(w, x+1,y+dy, dx,dy);
w->g[y+dy][x+dx+1] = ']';
w->g[y][x+1] = '.';
}
clear(w, x+dx,y+dy, dx,dy);
w->g[y+dy][x+dx] = w->g[y][x];
w->g[y][x] = '.';
}
static void
move(struct world *w, int dx, int dy)
{
if (can_clear(w, w->px+dx, w->py+dy, dx,dy)) {
clear(w, w->px+dx, w->py+dy, dx,dy);
w->px += dx;
w->py += dy;
}
}
static int
score(struct world *w)
{
int acc=0, x,y;
for (y=0; y<GH && w->g[y][0]; y++)
for (x=0; x<GW && w->g[y][x]; x++)
if (w->g[y][x] == 'O' || w->g[y][x] == '[')
acc += 100*y + x;
return acc;
}
int
main(int argc, char **argv)
{
static struct world w1,w2;
int x,y, c;
char *p;
if (argc > 1)
DISCARD(freopen(argv[1], "r", stdin));
for (y=0; fgets(w1.g[y], GW, stdin); y++) {
if (!w1.g[y][0] || w1.g[y][0]=='\n')
break;
assert(y+1 < GH);
assert(strlen(w1.g[y])*2+1 < GW);
for (x=0; w1.g[y][x]; x++)
if (w1.g[y][x] == 'O') {
w2.g[y][x*2] = '[';
w2.g[y][x*2+1] = ']';
} else {
w2.g[y][x*2] = w1.g[y][x];
w2.g[y][x*2+1] = w1.g[y][x];
}
if ((p = strchr(w1.g[y], '@'))) {
w1.py = y; w1.px = p-w1.g[y];
w2.py = y; w2.px = w1.px*2;
w1.g[w1.py][w1.px] = '.';
w2.g[w2.py][w2.px] = '.';
w2.g[w2.py][w2.px+1] = '.';
}
}
while ((c = getchar()) != EOF)
switch (c) {
case '^': move(&w1, 0,-1); move(&w2, 0,-1); break;
case 'v': move(&w1, 0, 1); move(&w2, 0, 1); break;
case '<': move(&w1,-1, 0); move(&w2,-1, 0); break;
case '>': move(&w1, 1, 0); move(&w2, 1, 0); break;
}
printf("15: %d %d\n", score(&w1), score(&w2));
return 0;
}
C#
beautiful
public class Day15 : Solver
{
private char[][] map;
private int width, height;
private string movements;
public void Presolve(string input) {
var blocks = input.Trim().Split("\n\n").ToList();
map = blocks[0].Split("\n").Select(line => line.ToArray()).ToArray();
width = map[0].Length;
height = map.Length;
movements = blocks[1];
}
public string SolveFirst() {
var data = map.Select(row => row.ToArray()).ToArray();
int robot_x = -1, robot_y = -1;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (data[j][i] == '@') {
robot_x = i;
robot_y = j;
data[j][i] = '.';
break;
}
}
}
foreach (var m in movements) {
var (dx, dy) = m switch {
'^' => (0, -1), '>' => (1, 0), 'v' => (0, 1), '<' => (-1, 0),
_ => (0, 0)
};
if ((dx, dy) == (0, 0)) continue;
var (x, y) = (robot_x + dx, robot_y + dy);
if (data[y][x] == '#') continue;
if (data[y][x] == '.') {
(robot_x, robot_y) = (x, y);
continue;
}
var (end_of_block_x, end_of_block_y) = (x + dx, y + dy);
while (data[end_of_block_y][end_of_block_x] == 'O') {
(end_of_block_x, end_of_block_y) = (end_of_block_x + dx, end_of_block_y + dy);
}
if (data[end_of_block_y][end_of_block_x] == '.') {
data[end_of_block_y][end_of_block_x] = 'O';
data[y][x] = '.';
(robot_x, robot_y) = (x, y);
}
}
long answer = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (data[j][i] == 'O') {
answer += i + 100 * j;
}
}
}
return answer.ToString();
}
public string SolveSecond() {
var expanded_data = map.Select(row => row.SelectMany<char, char>(ch => ch switch {
'#' => ['#', '#'], 'O' => ['[', ']'], '.' => ['.', '.'], '@' => ['@', '.'] }).ToArray()).ToArray();
int robot_x = -1, robot_y = -1;
for (int i = 0; i < width * 2; i++) {
for (int j = 0; j < height; j++) {
if (expanded_data[j][i] == '@') {
robot_x = i;
robot_y = j;
expanded_data[j][i] = '.';
break;
}
}
}
if (robot_x < 0) throw new InvalidDataException();
foreach (var m in movements) {
var (dx, dy) = m switch {
'^' => (0, -1), '>' => (1, 0), 'v' => (0, 1), '<' => (-1, 0),
_ => (0, 0)
};
if ((dx, dy) == (0, 0)) continue;
var (x, y) = (robot_x + dx, robot_y + dy);
if (expanded_data[y][x] == '#') continue;
if (expanded_data[y][x] == '.') {
(robot_x, robot_y) = (x, y);
continue;
}
if (dy == 0) {
var (end_of_block_x, end_of_block_y) = (x + dx * 2, y);
while (expanded_data[end_of_block_y][end_of_block_x] == '[' ||
expanded_data[end_of_block_y][end_of_block_x] == ']') {
(end_of_block_x, end_of_block_y) = (end_of_block_x + dx, end_of_block_y);
}
if (expanded_data[end_of_block_y][end_of_block_x] == '.') {
var (fill_start, fill_end) = dx > 0 ? (x + 1, end_of_block_x) : (end_of_block_x, x);
for (int fill_x = fill_start; fill_x < fill_end; fill_x += 2) {
expanded_data[y][fill_x] = '[';
expanded_data[y][fill_x + 1] = ']';
}
expanded_data[y][x] = '.';
(robot_x, robot_y) = (x, y);
}
continue;
}
List<(int, int)> boxes_to_move = [(x, y)];
if (expanded_data[y][x] == ']') {
boxes_to_move.Add((x - 1, y));
} else {
boxes_to_move.Add((x + 1, y));
}
List<(int, int)> boxes_move_ordered = [];
bool impossible = false;
while (boxes_to_move.Count > 0) {
HashSet<(int, int)> next_boxes = [];
foreach (var (box_x, box_y) in boxes_to_move) {
boxes_move_ordered.Add((box_x, box_y));
if (expanded_data[box_y + dy][box_x] == '.') continue;
if (expanded_data[box_y + dy][box_x] == '#') {
impossible = true;
break;
}
next_boxes.Add((box_x, box_y + dy));
if (expanded_data[box_y + dy][box_x] == ']') {
next_boxes.Add((box_x - 1, box_y + dy));
} else {
next_boxes.Add((box_x + 1, box_y + dy));
}
}
if (impossible) break;
boxes_to_move = [..next_boxes];
}
if (impossible) continue;
boxes_move_ordered.Reverse();
foreach (var (box_x, box_y) in boxes_move_ordered) {
expanded_data[box_y + dy][box_x] = expanded_data[box_y][box_x];
expanded_data[box_y][box_x] = '.';
}
(robot_x, robot_y) = (x, y);
}
long answer = 0;
for (int i = 0; i < width * 2; i++) {
for (int j = 0; j < height; j++) {
if (expanded_data[j][i] == '[') {
answer += i + 100 * j;
}
}
}
return answer.ToString();
}
}
Rust
The work is all in the βpushβ method. The robot pushes one square, which may chain to additional squares. HashSet probably isnβt the optimal data structure, but itβs good enough.
Large codeblock
/// Advent of Code 2024, Day 15
/// Copyright 2024 by Alex Utter
use aocfetch;
use std::collections::HashSet;
type Rc = (usize, usize);
type Delta = (isize, isize);
type Moves = Vec<Delta>;
fn add(rc:&Rc, mv:&Delta) -> Rc {
(rc.0.saturating_add_signed(mv.0),
rc.1.saturating_add_signed(mv.1))
}
struct Warehouse {
part2: bool,
robot: Rc,
boxes: HashSet<Rc>,
walls: HashSet<Rc>,
}
impl Warehouse {
fn new(input: &str, part2: bool) -> (Warehouse, Moves) {
let mut init = Warehouse {
part2: part2,
robot: (0,0),
boxes: HashSet::new(),
walls: HashSet::new(),
};
let mut moves = Vec::new();
for (r,line) in input.trim().lines().enumerate() {
for (c,ch) in line.trim().chars().enumerate() {
let c2 = if part2 {2*c} else {c};
match ch {
'@' => {init.robot = (r,c2);},
'O' => {init.boxes.insert((r,c2));},
'#' => {init.walls.insert((r,c2));
if part2 {init.walls.insert((r,c2+1));}},
'^' => {moves.push((-1, 0));},
'>' => {moves.push(( 0, 1));},
'v' => {moves.push(( 1, 0));},
'<' => {moves.push(( 0,-1));},
_ => {},
}
}
}
return (init, moves);
}
fn gps(&self) -> usize {
self.boxes.iter().map(|(r,c)| 100*r + c).sum()
}
fn get_box(&self, rc: &Rc) -> Option<Rc> {
let ll = add(rc, &(0,-1));
let rr = rc.clone();
if self.part2 && self.boxes.contains(&ll) {
return Some(ll);
} else if self.boxes.contains(&rr) {
return Some(rr);
} else {
return None;
}
}
fn push(&mut self, mv: &Delta) -> bool {
// Identify all boxes affected by this push.
let mut boxes = HashSet::new(); // List of affected boxes
let mut queue = Vec::new(); // Squares being pushed
queue.push(add(&self.robot, mv));
while let Some(rc) = queue.pop() {
if let Some(bx) = self.get_box(&rc) {
// Push all square(s) affected by this box.
let left = add(&bx, mv);
let right = add(&left, &(0,1));
boxes.insert(bx);
if left != rc {queue.push(left);}
if self.part2 && right != rc {queue.push(right);}
} else if self.walls.contains(&rc) {
// If we hit a wall, the move cannot be applied.
return false;
}
}
// Move successful, update the warehouse state.
self.robot = add(&self.robot, mv);
for bx in boxes.iter() {self.boxes.remove(bx);}
for bx in boxes.iter() {self.boxes.insert(add(bx, mv));}
return true;
}
}
fn part1(input: &str) -> usize {
let (mut state, moves) = Warehouse::new(input, false);
for mv in moves.iter() {state.push(mv);}
return state.gps();
}
fn part2(input: &str) -> usize {
let (mut state, moves) = Warehouse::new(input, true);
for mv in moves.iter() {state.push(mv);}
return state.gps();
}
const EXAMPLE1: &'static str = "\
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########
<^^>>>vv<v>>v<<";
const EXAMPLE2: &'static str = "\
##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########
<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^";
fn main() {
// Fetch input from server.
let input = aocfetch::get_data(2024, 15).unwrap();
assert_eq!(part1(EXAMPLE1), 2028);
assert_eq!(part1(EXAMPLE2), 10092);
assert_eq!(part2(EXAMPLE2), 9021);
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
Haskell
Runs in 12 ms. I was very happy with my code for part 1, but will sadly have to rewrite it completely for part 2.
Code
import Control.Monad.State.Lazy
import qualified Data.Map.Strict as M
type Coord = (Int, Int)
data Block = Box | Wall
type Grid = M.Map Coord Block
parse :: String -> ((Coord, Grid), [Coord])
parse s =
let robot = head
[ (r, c)
| (r, row) <- zip [0 ..] $ lines s
, (c, '@') <- zip [0 ..] row
]
grid = M.fromAscList
[ ((r, c), val)
| (r, row) <- zip [0 ..] $ lines s
, (c, Just val) <- zip [0 ..] $ map f row
]
in ((robot, grid), go s)
where
f 'O' = Just Box
f '#' = Just Wall
f _ = Nothing
go ('^' : rest) = (-1, 0) : go rest
go ('v' : rest) = ( 1, 0) : go rest
go ('<' : rest) = ( 0, -1) : go rest
go ('>' : rest) = ( 0, 1) : go rest
go (_ : rest) = go rest
go [] = []
add :: Coord -> Coord -> Coord
add (r0, c0) (r1, c1) = (r0 + r1, c0 + c1)
moveBoxes :: Coord -> Coord -> Grid -> Maybe Grid
moveBoxes dr r grid = case grid M.!? r of
Nothing -> Just grid
Just Wall -> Nothing
Just Box ->
M.insert (add r dr) Box . M.delete r <$> moveBoxes dr (add r dr) grid
move :: Coord -> State (Coord, Grid) Bool
move dr = state $ \(r, g) -> case moveBoxes dr (add r dr) g of
Just g' -> (True, (add r dr, g'))
Nothing -> (False, (r, g))
moves :: [Coord] -> State (Coord, Grid) ()
moves = mapM_ move
main :: IO ()
main = do
((robot, grid), movements) <- parse <$> getContents
let (_, grid') = execState (moves movements) (robot, grid)
print $ sum [100 * r + c | ((r, c), Box) <- M.toList grid']