|
| 1 | +--- |
| 2 | +title: "Day 25" |
| 3 | +date: 2024-12-25 |
| 4 | +author: |
| 5 | + name: https://adventofcode.com/2024/day/25 |
| 6 | + url: https://adventofcode.com/2024/day/25 |
| 7 | +--- |
| 8 | + |
| 9 | +## Setup |
| 10 | + |
| 11 | +```{r setup} |
| 12 | +# Libraries |
| 13 | +library(tidyverse) |
| 14 | +
|
| 15 | +# Read input from file |
| 16 | +input <- read_lines("../input/day25.txt", skip_empty_rows = FALSE) |
| 17 | +``` |
| 18 | + |
| 19 | +## Part 1 |
| 20 | + |
| 21 | +Convert input to lists of keys and locks by height: |
| 22 | + |
| 23 | +```{r} |
| 24 | +
|
| 25 | +groups <- input |> |
| 26 | + enframe(name = NULL) |> |
| 27 | + mutate(group_id = cumsum(value == ""), .before = everything()) |> |
| 28 | + filter(value != "") |> |
| 29 | + mutate( |
| 30 | + col = str_split(value, ""), |
| 31 | + row = row_number(), |
| 32 | + .by = group_id |
| 33 | + ) |> |
| 34 | + mutate( |
| 35 | + type = case_when(row == 1 ~ if_else(str_detect(value, "#"), "lock", "key")) |
| 36 | + ) |> |
| 37 | + fill(type, .direction = "down") |> |
| 38 | + unnest_wider(col, names_sep = "") |> |
| 39 | + mutate(group_id = str_c(type, "_", group_id)) |> |
| 40 | + select(-c(value, row, type, row)) |> |
| 41 | + group_split(group_id) |
| 42 | +
|
| 43 | +groups <- set_names( |
| 44 | + groups, |
| 45 | + map_chr(groups, ~ unique(pull(.x, group_id))) |
| 46 | +) |
| 47 | +
|
| 48 | +``` |
| 49 | + |
| 50 | +Transpose data frames and count pin heights of each column: |
| 51 | + |
| 52 | +```{r} |
| 53 | +
|
| 54 | +pins <- groups |> |
| 55 | + map( |
| 56 | + ~ .x |> |
| 57 | + select(-group_id) |> |
| 58 | + as.matrix() |> |
| 59 | + t() |> |
| 60 | + as_tibble() |> |
| 61 | + transmute(height = rowSums(across(everything(), ~ .x == "#")) - 1) |> |
| 62 | + pull(height) |
| 63 | + ) |
| 64 | +
|
| 65 | +locks <- keep_at(pins, ~ str_starts(.x, "lock")) |
| 66 | +keys <- keep_at(pins, ~ str_starts(.x, "key")) |
| 67 | +
|
| 68 | +``` |
| 69 | +Compute maximum height for any given lock/key combo: |
| 70 | + |
| 71 | +```{r} |
| 72 | +
|
| 73 | +max_height <- nrow(groups[[1]]) - 2 |
| 74 | +
|
| 75 | +``` |
| 76 | + |
| 77 | +Cross all locks with all keys and check for overlapping pins: |
| 78 | + |
| 79 | +```{r} |
| 80 | +
|
| 81 | +expand_grid(lock = locks, key = keys) |> |
| 82 | + mutate(fits = map2_lgl(lock, key, ~ max(.x + .y) <= max_height)) |> |
| 83 | + pull(fits) |> |
| 84 | + sum() |
| 85 | +
|
| 86 | +``` |
| 87 | + |
| 88 | + |
| 89 | + |
0 commit comments