library(tidyverse)
library(unglue)
Day 5
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from file:
<- read_lines("../input/day05.txt") input
Convert plain-text input to a dataframe of numeric values:
<- input |>
input_df unglue_data("{x1=\\d+},{y1=\\d+} -> {x2=\\d+},{y2=\\d+}", convert = TRUE) |>
mutate(id = row_number(), .before = everything())
Part 1
Flag each line segment as horizontal, vertical or diagonal. Then, compute the list of all integer points that fall along the line.
<- input_df |>
lines mutate(
type = case_when(
== x2 ~ "v",
x1 == y2 ~ "h",
y1 .default = "d"
),x = map2(x1, x2, ~ seq(..1, ..2)),
y = map2(y1, y2, ~ seq(..1, ..2))
|>
) unnest(cols = c(x, y))
Compute the number of points that are covered by at least 2 overlapping horizontal or vertical lines (diagonals excluded):
|>
lines filter(type %in% c("v", "h")) |>
summarize(n = n(), .by = c(x, y)) |>
filter(n > 1) |>
nrow()
Part 2
Repeat the count of overlapping points, now allowing diagonals:
|>
lines summarize(n = n(), .by = c(x, y)) |>
filter(n > 1) |>
nrow()