library(tidyverse)
Day 3
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file:
<- read_lines("../input/day03.txt") input
Parse character strings and convert into a 1/0 matrix:
<- input |>
mtx str_split("") |>
map(~ case_match(.x, "." ~ 0, "#" ~ 1)) |>
reduce(rbind) |>
unname()
Part 1
Define a function that converts a slope to indices:
<- function(mtx, right, down) {
slope_to_idx <- seq.int(1, nrow(mtx), by = down)
rows <- ((1:length(rows) - 1) * right) %% ncol(mtx) + 1
cols
array(c(rows, cols), dim = c(length(rows), 2))
}
Define a function to count the encountered trees, given a slope:
<- function(mtx, right, down) {
count_trees sum(mtx[slope_to_idx(mtx, right, down)])
}
Count the encountered trees for a slope of right 3, down 1:
count_trees(mtx, 3, 1)
Part 2
Compare the encountered trees when using the following slopes and take their product:
Right 1, down 1
Right 3, down 1
Right 5, down 1
Right 7, down 1
Right 1, down 2
<- c(1, 3, 5, 7, 1)
right <- c(1, 1, 1, 1, 2)
down
map2_dbl(right, down, \(right, down) count_trees(mtx, right, down)) |>
prod()