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