# Libraries
library(tidyverse)
library(ctmle, include.only = "bound")
# Read input from file
<- read_lines("../input/day09.txt") |>
input str_split(" ")
Day 9
Advent of Code: Worked Solutions
Setup
Part 1
# Convert head movements to sequence of locations on complex plane
<- input |>
head_path map(~ rep(.x[[1]], .x[[2]])) |>
reduce(c) |>
recode("R" = 1 + 0i, "L" = -1 + 0i, "U" = 0 + 1i, "D" = 0 - 1i) |>
accumulate(.init = 0 + 0i, .f = sum)
# Find path of next knot given path of previous knot.
<- function(prev_knot_path) {
move_next_knot accumulate(
.x = prev_knot_path,
.f = function(tail = .x, head = .y) {
<- head - tail
diff if_else(
max(abs(Re(diff)), abs(Im(diff))) <= 1,
tail,+ bound(Re(diff), c(-1, 1)) + bound(Im(diff), c(-1, 1)) * 1i
tail
)
}
) }
<- function(path, num_knots) {
unique_tail_spots # Iteratively compute path of each knot from head & to tail
<- reduce(map(1:(num_knots - 1), ~ move_next_knot), compose)
move_tail
# Find number of unique locations in the tail's path
length(unique(move_tail(path)))
}
unique_tail_spots(head_path, num_knots = 2)
[1] 6197
Part 2
unique_tail_spots(head_path, num_knots = 10)
[1] 2562