# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day20.txt", skip_empty_rows = TRUE) |>
input as.numeric()
Day 20
Advent of Code: Worked Solutions
Setup
Part 1
# Shift the value at the given index by n steps
<- function(vec, idx_old, n) {
shift_value <- (idx_old + n - 2) %% (length(vec) - 1) + 1
idx_new <- vec[idx_old]
value
|>
vec discard_at(idx_old) |>
append(value, after = idx_new)
}
# Mix the given list of integers in order by shifting values one-by-one
<- function(file, n = 1) {
mix <- 1:length(file)
ids
for (rep in 1:n) {
for (i in 1:length(file)) {
<- shift_value(ids, which(ids == i), file[i])
ids
}
}
file[ids]
}
# Sum the grove coordinates in a given vector
<- function(vec) {
grove_coords c(1000, 2000, 3000) |>
map_dbl(~ vec[(which(vec == 0) + .x) %% length(vec)]) |>
sum()
}
Run on puzzle input:
|>
input mix() |>
grove_coords()
[1] 2215
Part 2
Apply decryption key and mix 10 times:
* 811589153) |>
(input mix(n = 10) |>
grove_coords()
[1] 8927480683