# Libraries
library(tidyverse)
# Read input from file
<- "../input/day05.txt"
path <- read_lines(path) input
Day 5
Advent of Code: Worked Solutions
Setup
Part 1
# Format raw input
<- input |>
moves tail_while(~ .x != "") |>
str_extract_all("\\d+") |>
map(as.integer)
<- read_fwf(
stacks
path,n_max = length(input) - length(moves) - 2,
col_types = "c"
|>
) mutate(across(everything(), ~ str_extract(.x, "[A-Z]"))) |>
as.list() |>
map(discard, is.na) |>
map(rev)
<- function(moves, stacks, func) {
move_crates
# Execute moves
for (curr_move in moves) {
<- curr_move[1]
count <- curr_move[2]
from <- curr_move[3]
to
<- func(tail(stacks[[from]], count))
crates
<- append(stacks[[to]], crates)
stacks[[to]] <- head(stacks[[from]], -1 * count)
stacks[[from]]
}
# Examine final top row of crates
|>
stacks map(~ tail(.x, 1)) |>
str_c(collapse = "")
}
move_crates(moves, stacks, rev)
[1] "RLFNRTNFB"
Part 2
move_crates(moves, stacks, identity)
[1] "MHQTLJRLB"