Day 3: Perfectly Spherical Houses in a Vacuum

Reference

library(tidyverse)

input <- read_lines(file = "inputs/2015/03.txt")

Part One

moves <- tibble(input = c(NA, str_split_1(input, pattern = ""))) |> 
    mutate(move_x = case_match(input,
                               "^" ~ 0, ">" ~ 1, "v" ~ 0, "<" ~ -1,
                               .default = 0),
           move_y = case_match(input, 
                               "^" ~ 1, ">" ~ 0, "v" ~ -1, "<" ~ 0,
                               .default = 0),
           pos_x = cumsum(move_x),
           pos_y = cumsum(move_y))

houses_visited <- moves |> 
    distinct(pos_x, pos_y) |> 
    nrow()

cat("Houses visited:", houses_visited, "\n")
## Houses visited: 2081
moves |> 
    ggplot(mapping = aes(x = pos_x, y = pos_y)) +
    geom_path() +
    theme_bw()

Part Two

moves <- tibble(input = str_split_1(input, pattern = "")) |> 
    mutate(
        move_x = case_match(input, "^" ~ 0, ">" ~ 1, "v" ~ 0, "<" ~ -1),
        move_y = case_match(input, "^" ~ 1, ">" ~ 0, "v" ~ -1, "<" ~ 0),
        who = if_else(row_number() %% 2 == 1, "santa", "robo")
    ) |> 
    mutate(
        pos_x = cumsum(move_x),
        pos_y = cumsum(move_y),
        .by = who
    ) |> 
    add_row(pos_x = 0, pos_y = 0, who = "both", .before = 1)

houses_visited_p2 <- moves |>
    distinct(pos_x, pos_y) |>
    nrow()

cat("Houses visited with Robo-Santa:", houses_visited_p2, "\n")
## Houses visited with Robo-Santa: 2341
moves |> 
    ggplot(mapping = aes(x = pos_x, y = pos_y, col = who)) +
    geom_path() +
    theme_bw()