library(tidyverse)
library(unglue)
Day 13
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from file:
<- read_lines("../input/day13.txt", skip_empty_rows = TRUE) input
Split input from plain-text strings into (1) x/y dot coordinates, and (2) a set of fold instructions.
<- input |>
dots unglue_data("{x},{y}", convert = TRUE) |>
drop_na()
<- input |>
folds unglue_data("fold along {axis}={value}", convert = TRUE) |>
drop_na()
Part 1
Define a function to fold the paper with the list of dots over a given line:
<- function(df, axis, value) {
fold_paper |>
df mutate(across(all_of(axis), ~ case_when(
> value ~ value - (.x - value),
.x .default = .x
|>
))) distinct()
}
Count the dots after the first fold is complete:
fold_paper(dots, folds$axis[[1]], folds$value[[1]]) |>
nrow()
Part 2
Fold the paper completely:
<- reduce2(
folded .x = folds$axis,
.y = folds$value,
.f = \(acc, axis, value) fold_paper(acc, axis, value),
.init = dots
)
Print the output:
|>
folded mutate(chr = '#') |>
complete(x = full_seq(x, 1), y = full_seq(y, 1), fill = list("chr" = " ")) |>
arrange(y, x) |>
summarize(chr = str_flatten(chr), .by = y) |>
pull(chr) |>
cat(sep = "\n")