skip to content

AOC 22 Day 5 🏗️

Advent of Code 2022 Day 5 - Supply Stacks - Supplies in marked crates must be rearranged by a giant cargo crane in a series of planned steps to ensure they don't get crushed or fall over. Once rearranged, the desired crates will be at the top of each stack.

Problem🤔

Supply Stacks: The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.

The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.

The Elves don’t want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.

They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input)

Sample Data

For example, consider the following drawing

    [D]
[N] [C]
[Z] [M] [P]
 1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
    [D]
[N] [C]
[Z] [M] [P]
 1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.

Then, the rearrangement procedure is given.

Part 1

In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:

[D]
[N] [C]
[Z] [M] [P]
 1   2   3
[D]
[N] [C]
[Z] [M] [P]
 1   2   3

In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved D ends up below the second and third crates:

        [Z]
        [N]
    [C] [D]
    [M] [P]
 1   2   3
        [Z]
        [N]
    [C] [D]
    [M] [P]
 1   2   3

Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:

        [Z]
        [N]
[M]     [D]
[C]     [P]
 1   2   3
        [Z]
        [N]
[M]     [D]
[C]     [P]
 1   2   3

Finally, one crate is moved from stack 1 to stack 2:

        [Z]
        [N]
        [D]
[C] [M] [P]
 1   2   3
        [Z]
        [N]
        [D]
[C] [M] [P]
 1   2   3

The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.

After the rearrangement procedure completes, what crate ends up on top of each stack?

Solution 1💡

import { input } from './input.ts';
 
// Find the index of the string 'move' in the input
const indexOfMove = input.indexOf('move');
 
// Split the input into two parts: crates and move data
const crates = input.slice(0, indexOfMove);
const moveData = input.slice(indexOfMove);
 
// Split the crates part into rows, removing empty rows
const cratesRows = crates.split('\n').filter((x) => x);
 
// Get the numbers of the crates from the last
// row of the crates part of the input
const cratesNum = cratesRows
  // Get the last row and remove any whitespace
  .pop()
  ?.replaceAll(' ', '')
  // Convert each character to a number
  .split('')
  .map((x) => +x)!;
 
// Get the letters of the crates from the first three
// rows of the crates part of the input
const crateLetters = cratesRows.map((r) =>
  // Remove any whitespace and brackets
  r
    .replaceAll('  ', ' ')
    .replaceAll('[', '')
    .replaceAll(']', '')
    // Get only the even-indexed characters (which are the letters)
    .split('')
    .filter((_x, i) => i % 2 === 0)
);
 
// Create an object that maps crate numbers to arrays of letters
const crateList: Record<number, string[]> = {};
 
// Initialize the arrays of letters for each crate number
cratesNum.forEach((num, i) => {
  crateList[num] = [];
  crateLetters.forEach((l) => {
    // Get the letter for the ith column in the row of letters
    const letter = l.at(i)?.trim();
    if (letter) {
      // Add the letter to the array for the corresponding crate
      crateList[num].unshift(letter);
    }
  });
});
 
// Parse the move data into an array of arrays of numbers
const moves = moveData
  // Split the move data into lines
  .split('\n')
  // Split each line into space-separated words,
  //convert to numbers, and remove any empty values
  .map((x) =>
    x
      .split(' ')
      .map((x) => +x)
      .filter((x) => x)
  );
 
// Loop through each move
moves.forEach(([num, from, to]) => {
  // For each move, pop the specified number of crates
  // from the "from" stack and push them to the "to" stack
  for (let i = 0; i < num; i++) {
    crateList[to].push(crateList[from].pop()!);
  }
});
 
// Create an empty string to store the top crate letters
let topCrates = '';
 
// Loop through each stack of crates
cratesNum.forEach((n) => {
  // Add the top crate letter from each stack to the string
  topCrates += crateList[n].at(-1);
});
 
// Print the final string of top crate letters
console.log(topCrates);
import { input } from './input.ts';
 
// Find the index of the string 'move' in the input
const indexOfMove = input.indexOf('move');
 
// Split the input into two parts: crates and move data
const crates = input.slice(0, indexOfMove);
const moveData = input.slice(indexOfMove);
 
// Split the crates part into rows, removing empty rows
const cratesRows = crates.split('\n').filter((x) => x);
 
// Get the numbers of the crates from the last
// row of the crates part of the input
const cratesNum = cratesRows
  // Get the last row and remove any whitespace
  .pop()
  ?.replaceAll(' ', '')
  // Convert each character to a number
  .split('')
  .map((x) => +x)!;
 
// Get the letters of the crates from the first three
// rows of the crates part of the input
const crateLetters = cratesRows.map((r) =>
  // Remove any whitespace and brackets
  r
    .replaceAll('  ', ' ')
    .replaceAll('[', '')
    .replaceAll(']', '')
    // Get only the even-indexed characters (which are the letters)
    .split('')
    .filter((_x, i) => i % 2 === 0)
);
 
// Create an object that maps crate numbers to arrays of letters
const crateList: Record<number, string[]> = {};
 
// Initialize the arrays of letters for each crate number
cratesNum.forEach((num, i) => {
  crateList[num] = [];
  crateLetters.forEach((l) => {
    // Get the letter for the ith column in the row of letters
    const letter = l.at(i)?.trim();
    if (letter) {
      // Add the letter to the array for the corresponding crate
      crateList[num].unshift(letter);
    }
  });
});
 
// Parse the move data into an array of arrays of numbers
const moves = moveData
  // Split the move data into lines
  .split('\n')
  // Split each line into space-separated words,
  //convert to numbers, and remove any empty values
  .map((x) =>
    x
      .split(' ')
      .map((x) => +x)
      .filter((x) => x)
  );
 
// Loop through each move
moves.forEach(([num, from, to]) => {
  // For each move, pop the specified number of crates
  // from the "from" stack and push them to the "to" stack
  for (let i = 0; i < num; i++) {
    crateList[to].push(crateList[from].pop()!);
  }
});
 
// Create an empty string to store the top crate letters
let topCrates = '';
 
// Loop through each stack of crates
cratesNum.forEach((n) => {
  // Add the top crate letter from each stack to the string
  topCrates += crateList[n].at(-1);
});
 
// Print the final string of top crate letters
console.log(topCrates);

It begins by splitting the input into two parts, the crate data and the move data.

The crate data is then split into individual rows and numbers, and the letters from each row are extracted and stored in an object with the corresponding number as the key.

The move data is split into individual moves and each move is mapped to an array of three numbers.

The moves are then looped through and applied to the crate data by moving the specified number of crates from the source stack to the destination stack.

The final top crates are then extracted and concatenated into a string, which is logged to the console.

Part 2

As you watch the crane operator expertly rearrange the crates, you notice the process isn’t following your prediction.

Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn’t a CrateMover 9000 - it’s a CrateMover 9001.

The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.

Again considering the example above, the crates begin in the same configuration:

    [D]
[N] [C]
[Z] [M] [P]
 1   2   3
    [D]
[N] [C]
[Z] [M] [P]
 1   2   3

Moving a single crate from stack 2 to stack 1 behaves the same as before:

[D]
[N] [C]
[Z] [M] [P]
 1   2   3
[D]
[N] [C]
[Z] [M] [P]
 1   2   3

However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:

        [D]
        [N]
    [C] [Z]
    [M] [P]
 1   2   3
        [D]
        [N]
    [C] [Z]
    [M] [P]
 1   2   3

Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:

        [D]
        [N]
[C]     [Z]
[M]     [P]
 1   2   3
        [D]
        [N]
[C]     [Z]
[M]     [P]
 1   2   3

Finally, a single crate is still moved from stack 1 to stack 2, but now it’s crate C that gets moved:

        [D]
        [N]
        [Z]
[M] [C] [P]
 1   2   3
        [D]
        [N]
        [Z]
[M] [C] [P]
 1   2   3

In this example, the CrateMover 9001 has put the crates in a totally different order: MCD.

Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies.

After the rearrangement procedure completes, what crate ends up on top of each stack?

Solution 2💡

// Loop through each move
moves.forEach(([num, from, to]) => {
  // Find the tail of the from stack, which is the last num elements
  const tail = crateList[from].splice(crateList[from].length - num);
 
  // Add the tail to the end of the to stack
  crateList[to].push(...tail);
});
// Loop through each move
moves.forEach(([num, from, to]) => {
  // Find the tail of the from stack, which is the last num elements
  const tail = crateList[from].splice(crateList[from].length - num);
 
  // Add the tail to the end of the to stack
  crateList[to].push(...tail);
});

For part 2 we only need to the modify the loop from part 1.

This code loops through each move in the moves array, and for each move it takes the last num items instead of just 1 from the from stack, and adds them to the to stack. The from stack is updated in-place, with the items removed from it. The tail variable is a temporary variable that holds the removed items before they are added to the to stack.