Skip to content

Instantly share code, notes, and snippets.

@statzhero
Created December 12, 2023 15:22
Show Gist options
  • Save statzhero/1295412775114ddf2017e05544a5ddf3 to your computer and use it in GitHub Desktop.
Save statzhero/1295412775114ddf2017e05544a5ddf3 to your computer and use it in GitHub Desktop.
Advent of Code day 10
library(tidyverse)
d <- read_table("./inst/input10.txt", col_names = FALSE) |>
separate_longer_position(X1, 1) |>
mutate(dist = if_else(X1 == "S", 0, NA)) |>
mutate(x = if_else(X1 == "S", "L", X1)) # eyeballing
NCOL <- sqrt(nrow(d))
top <- c("7", "|", "F")
bottom <- c("J", "|", "L")
left <- c("L", "-", "F")
right <- c("J", "-", "7")
follow_pipe <- function(dta, i){
mutate(dta, dist = case_when(
x == "|" & lag(dist, NCOL) == i & (lag(x, NCOL) %in% top) ~ i + 1,
x == "|" & lead(dist, NCOL) == i & (lead(x, NCOL) %in% bottom) ~ i + 1,
x == "-" & lag(dist, 1) == i & (lag(x, 1) %in% left) ~ i + 1,
x == "-" & lead(dist, 1) == i & (lead(x, 1) %in% right) ~ i + 1,
x == "F" & lead(dist, 1) == i & (lead(x, 1) %in% right) ~ i + 1,
x == "F" & lead(dist, NCOL) == i & (lead(x, NCOL) %in% bottom) ~ i + 1,
x == "7" & lag(dist, 1) == i & (lag(x, 1) %in% left) ~ i + 1,
x == "7" & lead(dist, NCOL) == i & (lead(x, NCOL) %in% bottom) ~ i + 1,
x == "J" & lag(dist, NCOL) == i & (lag(x, NCOL) %in% top) ~ i + 1,
x == "J" & lag(dist, 1) == i & (lag(x, 1) %in% left) ~ i + 1,
x == "L" & lag(dist, NCOL) == i & (lag(x, NCOL) %in% top) ~ i + 1,
x == "L" & lead(dist, 1) == i & (lead(x, 1) %in% right) ~ i + 1,
.default = dist))
}
measure_pipe <- function(x){
x <- x |> filter(!is.na(dist))
nrow(x) / 2 # we only get an even number when loop is closed
}
i <- 0 # for-loop is safer but slower
while (floor(measure_pipe(d)) != measure_pipe(d)) {
d <- follow_pipe(d, i)
i <- i + 1
}
# part 2 - a ray crossing will be inside at odd counts
p <- d |> mutate(pipe = if_else(!is.na(dist), x, NA)) |>
pull(pipe) |> matrix(ncol = NCOL, byrow = TRUE)
inner_ray <- p |>
# pain: the corners
apply(2, \(x) cumsum(x %in% left)) |>
apply(2, \(x) x %% 2 != 0) # odd ray count
not_pipe <- p |> apply(2, is.na)
reduce(inner_ray * not_pipe, sum) # NOT matrix multiplication
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment