Task 19

Thorn Thaler - <

2026-02-11

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(rlang)
library(igraph)

1.2 Retrieve Data from AoC

session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
              session_cookie) %>% 
  content(encoding = "UTF-8") %>% 
  xml_find_all("///article") %>% 
  lapply(as.character)

parse_puzzle_data <- function(text_block = readClipboard()) {
  if (length(text_block) == 1L) {
    text_block <- text_block %>% 
      str_split("\n") %>% 
      extract2(1L)
  }
  sep <- which(!nzchar(text_block))
  parse_rule <- function(line) {
    rules <- str_remove_all(line, "^[a-z]+\\{|\\}")  %>% 
      str_extract_all("[^,]+") %>% 
      extract2(1L)
    is_dflt <- str_which(rules, ":", TRUE)
    rules <- str_replace_all(rules, ":(.*)", " ~ \"\\1\"")
    rules[is_dflt] <- paste0("TRUE ~ \"", rules[is_dflt], "\"")
    call2("case_when", !!!parse_exprs(rules))
  }
  parse_rules_lims <- function(line) {
    nm <- str_extract(line, "^\\w+")
    rule <- str_remove_all(line, "^\\w+\\{|\\}")
    dflt <- str_remove_all(line, "^.+,|\\}$")
    mtch <- str_match_all(rule, "([xmas])([<>])(\\d+):(\\w+)") %>% 
      extract2(1L)
    n <- nrow(mtch)
    res <- tibble(
      id = paste(nm, 1:n, sep = "_"),
      rule_nm = nm,
      order = 1:n,
      var = mtch[, 2L],
      val = as.integer(mtch[, 4]) + (mtch[, 3L] == ">")
    )
    res %>% 
      mutate(
        next_rule = lead(id) %>% 
          coalesce(dflt),
        target_true = if_else(mtch[, 3L] == ">", next_rule, mtch[, 5L]),
        target_false = if_else(mtch[, 3L] == ">", mtch[, 5L], next_rule)
      ) %>%
      mutate(across(starts_with("target"), 
                    ~ if_else(!str_detect(.x, "_\\d+$") & 
                                !str_detect(.x, "^[AR]$"),
                              paste0(.x, "_1"),
                              .x))) %>% 
      select(-next_rule)
  }
  rules <- text_block[1:(sep[1L] - 1L)]
  vals <- text_block[(sep[1L] + 1L):(length(text_block) - 1)] %>% 
    str_extract_all("\\d+") %>% 
    do.call(rbind, .) %>% 
    set_colnames(c("x", "m", "a", "s")) %>% 
    as_tibble() %>% 
    mutate(across(everything(), as.integer))
  nms <- str_extract_all(rules, "^[a-z]+")
  rules_lims <- map(rules, parse_rules_lims) %>% 
    list_rbind()
  rules <- map(rules, parse_rule) %>% 
    set_names(nms)
  
  list(vals = vals, rules = rules, rules_lims = rules_lims)
}

puzzle_data <- local({
  GET(paste0(base_url, "/input"),
      session_cookie) %>% 
    content(encoding = "UTF-8") %>% 
    parse_puzzle_data()
})

2 Puzzle Day 19

2.1 Part 1

2.1.1 Description

— Day 19: Aplenty —

The Elves of Gear Island are thankful for your help and send you on your way. They even have a hang glider that someone stole from Desert Island; since you’re already going that direction, it would help them a lot if you would use it to get down there and return it to them.

As you reach the bottom of the relentless avalanche of machine parts, you discover that they’re already forming a formidable heap. Don’t worry, though - a group of Elves is already here organizing the parts, and they have a system.

To start, each part is rated in each of four categories:

  • x: Extremely cool looking
  • m: Musical (it makes a noise when you hit it)
  • a: Aerodynamic
  • s: Shiny

Then, each part is sent through a series of workflows that will ultimately accept or reject the part. Each workflow has a name and contains a list of rules; each rule specifies a condition and where to send the part if the condition is true. The first rule that matches the part being considered is applied immediately, and the part moves on to the destination described by the rule. (The last rule in each workflow has no condition and always applies if reached.)

Consider the workflow ex{x>10:one,m<20:two,a>30:R,A}. This workflow is named ex and contains four rules. If workflow ex were considering a specific part, it would perform the following steps in order:

  • Rule “x>10:one”: If the part’s x is more than 10, send the part to the workflow named one.
  • Rule “m<20:two”: Otherwise, if the part’s m is less than 20, send the part to the workflow named two.
  • Rule “a>30:R”: Otherwise, if the part’s a is more than 30, the part is immediately rejected (R).
  • Rule “A”: Otherwise, because no other rules matched the part, the part is immediately accepted (A).

If a part is sent to another workflow, it immediately switches to the start of that workflow instead and never returns. If a part is accepted (sent to A) or rejected (sent to R), the part immediately stops any further processing.

The system works, but it’s not keeping up with the torrent of weird metal shapes. The Elves ask if you can help sort a few parts and give you the list of workflows and some part ratings (your puzzle input). For example:

px{a<2006:qkq,m>2090:A,rfg}
pv{a>1716:R,A}
lnx{m>1548:A,A}
rfg{s<537:gd,x>2440:R,A}
qs{s>3448:A,lnx}
qkq{x<1416:A,crn}
crn{x>2662:A,R}
in{s<1351:px,qqz}
qqz{s>2770:qs,m<1801:hdj,R}
gd{a>3333:R,R}
hdj{m>838:A,pv}

{x=787,m=2655,a=1222,s=2876}
{x=1679,m=44,a=2067,s=496}
{x=2036,m=264,a=79,s=2244}
{x=2461,m=1339,a=466,s=291}
{x=2127,m=1623,a=2188,s=1013}

The workflows are listed first, followed by a blank line, then the ratings of the parts the Elves would like you to sort. All parts begin in the workflow named in. In this example, the five listed parts go through the following workflows:

  • {x=787,m=2655,a=1222,s=2876}: in -> qqz -> qs -> lnx -> A
  • {x=1679,m=44,a=2067,s=496}: in -> px -> rfg -> gd -> R
  • {x=2036,m=264,a=79,s=2244}: in -> qqz -> hdj -> pv -> A
  • {x=2461,m=1339,a=466,s=291}: in -> px -> qkq -> crn -> R
  • {x=2127,m=1623,a=2188,s=1013}: in -> px -> rfg -> A

Ultimately, three parts are accepted. Adding up the x, m, a, and s rating for each of the accepted parts gives 7540 for the part with x=787, 4623 for the part with x=2036, and 6951 for the part with x=2127. Adding all of the ratings for all of the accepted parts gives the sum total of 19114.

Sort through all of the parts you’ve been given; what do you get if you add together all of the rating numbers for all of the parts that ultimately get accepted?

2.1.2 Solution

For the first part we constructed unevaluated case_when calls from the rules. We loop through all rules and apply them in the context of the data frame containing the piece values. The case_when statements return the next rule to apply. We continue this process until each tile falls either in the R or A category. Eventually we build the checksum from the accepted pieces and return it.

sort_pieces <- function(factory) {
  pieces <- factory$vals
  rules <- factory$rules
  pieces <- pieces %>% 
    mutate(rule_target = "in")
  while (!all(pieces$rule_target %in% c("R", "A"))) {
    pieces <- pieces %>% 
      mutate(rule = rules[rule_target]) %>% 
      rowwise() %>% 
      mutate(rule_target = if (rule_target %in% c("R", "A")) rule_target 
                               else eval_tidy(rule))
  }
  pieces %>% 
    filter(rule_target == "A") %>% 
    mutate(rating = x + m + a + s) %>% 
    summarize(rating = sum(rating)) %>% 
    pull(rating) %>% 
    sum()
}

sort_pieces(puzzle_data)
## [1] 418498

2.2 Part 2

2.2.1 Description

— Part Two —

Even with your help, the sorting process still isn’t fast enough.

One of the Elves comes up with a new plan: rather than sort parts individually through all of these workflows, maybe you can figure out in advance which combinations of ratings will be accepted or rejected.

Each of the four ratings (x, m, a, s) can have an integer value ranging from a minimum of 1 to a maximum of 4000. Of all possible distinct combinations of ratings, your job is to figure out which ones will be accepted.

In the above example, there are 167409079868000 distinct combinations of ratings that will be accepted.

Consider only your list of workflows; the list of part ratings that the Elves wanted you to sort is no longer relevant. How many distinct combinations of ratings will be accepted by the Elves’ workflows?

2.2.2 Solution

For the second part, we first construct a graph from the rules. Each node has 2 children, one if the condition is TRUE and one if the condition is FALSE. (N.B. to avoid many if clauses we transformed all the comparisons to a less-than-x form, that is instead of looking at if x > 2 then A else B we said if x < 3 then B else A).

Once the graph is constructed, we sort it topologically and update the limits of allowed values for each node. These limits can be derived from the parent’s limit as well as the receptive condition at the node.

Eventually, we propagated all the intervals to A (and R), where we have to multiply their lenghts and add all productes from all parents of A. Since the intervals where of the form [lwr, upr), i.e. the upper limit was not part of the interval, we really just need to look at the diff and do not need to add 1.

construct_graph <- function(rules) {
  vertices <- rules %>%
    mutate(
      id,
      label = paste0(id, ":\n", var, " < ", val),
      var,
      val,
      .keep = "none"
    )
  vertices <- bind_rows(
    vertices,
    tibble(id = c("R", "A"), label = id, var = NA_character_, val = NA_integer_)
  )
  ## use c(rbind(.)) trick to interweave values
  n <- nrow(rules)
  edges <- tibble(
    from = rep(rules$id, each = 2),
    to = c(rbind(rules$target_true, rules$target_false)), 
    label = rep(c("T", "F"), n),
    result = rep(c(TRUE, FALSE), n)
  )
  graph_from_data_frame(edges, directed = TRUE, vertices)
}

count_combinations <- function(rules) {
  G <- construct_graph(rules)
  nodes <- topo_sort(G)
  for (v in nodes) {
    parents <- neighbors(G, v, "in")
    if (length(parents) == 0L) {
      ## start node
      iv <- c(1L, 4001L)
      V(G)[v]$lims <- list(list(x = iv, m = iv, a = iv, s = iv))
    } else if (length(parents) == 1L) {
      edge <- E(G)[parents %->% v]
      V(G)[v]$lims <- parents$lims
      iv <- parents$lims[[1L]][[parents$var]]
      if (edge$result) {
        new_iv <- c(iv[1L], min(iv[2L], parents$val))
      } else {
        new_iv <- c(max(iv[1L], parents$val), iv[2L])
      }
      V(G)[v]$lims[[1L]][[parents$var]] <- new_iv
    } else {
      V(G)[v]$cnt <- 0L
      parents <- unique(parents)
      for (p in parents) {
        parent <- V(G)[p]
        edges <- E(G)[parent %->% v]
        for (e in edges) {
          edge <- E(G)[e]
          lims <- parent$lims[[1L]]
          iv <- lims[[parent$var]]
          if (edge$result) {
            new_iv <- c(iv[1L], min(iv[2L], parent$val))
          } else {
            new_iv <- c(max(iv[1L], parent$val), iv[2L])
          }
          lims[[parent$var]] <- new_iv
          n_cand <- map_dbl(lims, diff) %>% 
            prod()
          V(G)[v]$cnt <- V(G)[v]$cnt + n_cand
        }
      }
    }
  }
  V(G)["A"]$cnt
}
count_combinations(puzzle_data$rules_lims) %>% 
  print(digit = 16L)
## [1] 123331556462603