1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
1.2 Retrieve Data from AoC
session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
session_cookie) %>%
content(encoding = "UTF-8") %>%
xml_find_all("///article") %>%
lapply(as.character)
parse_puzzle_data <- function(text_block = readClipboard()) {
if (length(text_block) == 1L) {
text_block <- text_block %>%
str_split("\n") %>%
extract2(1L) %>%
keep(nzchar)
}
text_block %>%
str_split(",") %>%
map(~ tibble(
dir = str_sub(.x, 1L, 1L),
dis = as.integer(str_sub(.x, 2L))
))
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 3
2.1 Part 1
2.1.1 Description
— Day 3: Crossed Wires —
The gravity assist was successful, and you’re well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn’t completely installed, so that’s next on the priority list.
Opening the front panel reveals a jumble of wires. Specifically, two wires are connected to a central port and extend outward on a grid. You trace the path each wire takes as it leaves the central port, one wire per line of text (your puzzle input).
The wires twist and turn, but the two wires occasionally cross paths. To fix the circuit, you need to find the intersection point closest to the central port. Because the wires are on a grid, use the Manhattan distance for this measurement. While the wires do technically cross right at the central port where they both start, this point does not count, nor does a wire count as crossing with itself.
For example, if the first wire’s path is R8,U5,L5,D3, then starting from the central port (o), it goes right 8, up 5, left 5, and finally down 3:
...........
...........
...........
....+----+.
....|....|.
....|....|.
....|....|.
.........|.
.o-------+.
...........
Then, if the second wire’s path is U7,R6,D4,L4, it goes up 7, right 6, down 4, and left 4:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
These wires cross at two locations (marked X), but the lower-left one is closer to the central port: its distance is 3 + 3 = 6.
Here are a few more examples:
-
R75,D30,R83,U83,L12,D49,R71,U7,L72= distance
U62,R66,U55,R34,D71,R55,D58,R83159 -
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51= distance
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7135
What is the Manhattan distance from the central port to the closest intersection?
2.1.2 Solution
First, we determine the maximum steps taken to all diretcions to be able to size the
matrix accordingly. Then, we loop through all instructions an place the wire marker on the
fileds as indicated. If we hit an already occupied filed for the second wire, we mark it
with X. Eventually, we get the Manhattan distance from the start to all fields marked
with X.
print.wires <- function(x, ...) {
apply(x, 1, paste, collapse = "") %>%
paste(collapse = "\n") %>%
cat()
invisible(x)
}
create_grid <- function(wire_dir = puzzle_data) {
## first get extension for both wires
get_dim <- function(wire) {
wire %>%
mutate(
dx = case_when(
dir == "R" ~ dis,
dir == "L" ~ -dis,
TRUE ~ 0L),
dy = case_when(
dir == "D" ~ dis,
dir == "U" ~ -dis,
TRUE ~ 0L),
x = cumsum(dx),
y = cumsum(dy)
) %>%
summarize(
across(x:y, list(min = ~ min(c(0L, .x)),
max = ~ max(c(0L, .x))))
)
}
dims <- map(wire_dir, get_dim) %>%
reduce(~ tibble(
x_min = min(.x$x_min, .y$x_min),
x_max = max(.x$x_max, .y$x_max),
y_min = min(.x$y_min, .y$y_min),
y_max = max(.x$y_max, .y$y_max)
))
wires <- matrix(".",
dims$y_max - dims$y_min + 1L,
dims$x_max - dims$x_min + 1L)
class(wires) <- "wires"
center <- cbind(
if_else(dims$y_min < 0, abs(dims$y_min) + 1L, 1L),
if_else(dims$x_min < 0, abs(dims$x_min) + 1L, 1L))
wires[center] <- "O"
path_length <- wires
path_length[] <- 0L
storage.mode(path_length) <- "integer"
for (j in seq_along(wire_dir)) {
pos <- center
wire <- wire_dir[[j]]
old_path_length <- path_length
path_length[] <- .Machine$integer.max
path <- 0L
for (i in seq_len(nrow(wire))) {
dir <- wire %>%
slice(i)
if (dir$dir %in% c("L", "R")) {
offset <- if_else(dir$dir == "L", -1L, 1L)
idx <- cbind(pos[1L],
seq(pos[2L] + offset,
by = offset,
length.out = dir$dis)
)
} else {
offset <- if_else(dir$dir == "U", -1L, 1L)
idx <- cbind(seq(pos[1L] + offset, by = offset,
length.out = dir$dis),
pos[2L])
}
path <- path + seq(1L, length.out = dir$dis)
markers <- if_else(!wires[idx] %in% c(".", j), "X", as.character(j))
wires[idx] <- markers
path_length[idx] <- pmin(path_length[idx], path)
path <- tail(path, 1L)
pos <- tail(idx, 1L)
}
}
crossings <- which(wires == "X", arr.ind = TRUE)
steps <- cbind(
path1 = old_path_length[crossings],
path2 = path_length[crossings])
attr(wires, "center") <- center
attr(wires, "steps") <- steps
wires
}
follow_wires <- function(wires) {
x_pos <- which(wires == "X", arr.ind = TRUE)
center <- attr(wires, "center")
sweep(x_pos, 2L, c(center), "-") %>%
abs() %>%
rowSums() %>%
min()
}
grid <- create_grid(puzzle_data)
follow_wires(grid)
## [1] 217
2.2 Part 2
2.2.1 Description
— Part Two —
It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay.
To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires’ steps is lowest. If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection.
The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
In the above example, the intersection closest to the central port is reached after 8+5+5+2 = 20 steps by the first wire and 7+6+4+3 = 20 steps by the second wire for a total of 20+20 = 40 steps.
However, the top-right intersection is better: the first wire takes only 8+5+2 = 15 and the second wire takes only 7+6+2 = 15, a total of 15+15 = 30 steps.
Here are the best steps for the extra examples from above:
-
R75,D30,R83,U83,L12,D49,R71,U7,L72=
U62,R66,U55,R34,D71,R55,D58,R83610steps -
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51=
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7410steps
What is the fewest combined steps the wires must take to reach an intersection?
2.2.2 Solution
For the second part, we keep track of the path length, and store it for the intersection points. Then we just have to return the minimum step sum for any of the intersections.
find_min_steps <- function(grid) {
attr(grid, "steps") %>%
rowSums() %>%
min()
}
find_min_steps(grid)
## [1] 3454