Advent of Code - Day 5: Supply Stacks

Fifth day of the advent of code using R

advent of code
Published

December 5, 2022

Part 1

Input

Full

input <- readLines("input.txt")

head(input, 10)
 [1] "        [M]     [B]             [N]" "[T]     [H]     [V] [Q]         [H]"
 [3] "[Q]     [N]     [H] [W] [T]     [Q]" "[V]     [P] [F] [Q] [P] [C]     [R]"
 [5] "[C]     [D] [T] [N] [N] [L] [S] [J]" "[D] [V] [W] [R] [M] [G] [R] [N] [D]"
 [7] "[S] [F] [Q] [Q] [F] [F] [F] [Z] [S]" "[N] [M] [F] [D] [R] [C] [W] [T] [M]"
 [9] " 1   2   3   4   5   6   7   8   9 " ""                                   

Libraries

library(tidyverse)

Code

# Detect where initial state and procedure are separated
sep <- which(input == "")

# Split initial state of boxes with procedure steps
boxes <- input[1:(sep-2)]
procedure <- input[(sep+1):length(input)] %>% 
  str_extract_all("\\d+") %>% 
  map(as.integer)

# Count the number of stack to compute the indexes of the relevant character indexes to catch
stack_number <- max(str_count(string = boxes,"\\w"))
boxes_location <- seq(1,(stack_number*4 - 1), by = 4)+1

# Reconstruct stacks in a list of vectors
stacks <- 
  map(boxes_location, ~ str_sub(boxes, .x, .x)) %>%
  map(setdiff, c("", " ")) %>%
  map(rev)


# Launch the simulation
for (step in procedure) {
    
  qty <- step[1]
  from <- step[2]
  to <- step[3]
  
  stacks[[to]] <- c(stacks[[to]], rev(tail(stacks[[from]],qty))) # boxes are 
  # moved (they are reversed since the top ones need to be move before lower ones)
  
  stacks[[from]] <- stacks[[from]][1:(length(stacks[[from]])-qty)] # moved boxes 
  # are removed from their original stack
}


# We get the top box (last character of stack vector) for each stack
result <- unlist(map(stacks, tail, 1))

Result

The crates at the top of each stacks are FRDSQRRCD.

Part 2

Code

stacks <- 
  map(boxes_location, ~ str_sub(boxes, .x, .x)) %>%
  map(setdiff, c("", " ")) %>%
  map(rev)

# Launch the simulation
for (step in procedure) {
    
  qty <- step[1]
  from <- step[2]
  to <- step[3]
  
  stacks[[to]] <- c(stacks[[to]], tail(stacks[[from]],qty)) # boxes are 
  # moved (they are NOT reversed since its the CrateMover 9001)
  
  stacks[[from]] <- stacks[[from]][1:(length(stacks[[from]])-qty)] # moved boxes 
  # are removed from their original stack
}


# We get the top box (last character of stack vector) for each stack
result <- unlist(map(stacks, tail, 1))

Result

The crates at the top of each stacks are HRFTQVWNN.