Task 24

Thorn Thaler - <

2025-10-02

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(digest)

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) %>% 
      keep(nzchar)
  }
  text_block %>% 
    str_split("/") %>% 
    map(as.integer)
}

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

2 Puzzle Day 24

2.1 Part 1

2.1.1 Description

— Day 24: Electromagnetic Moat —

The CPU itself is a large, black building surrounded by a bottomless pit. Enormous metal tubes extend outward from the side of the building at regular intervals and descend down into the void. There’s no way to cross, but you need to get inside.

No way, of course, other than building a bridge out of the magnetic components strewn about nearby.

Each component has two ports, one on each end. The ports come in all different types, and only matching types can be connected. You take an inventory of the components by their port types (your puzzle input). Each port is identified by the number of pins it uses; more pins mean a stronger connection for your bridge. A 3/7 component, for example, has a type-3 port on one side, and a type-7 port on the other.

Your side of the pit is metallic; a perfect surface to connect a magnetic, zero-pin port. Because of this, the first port you use must be of type 0. It doesn’t matter what type of port you end with; your goal is just to make the bridge as strong as possible.

The strength of a bridge is the sum of the port types in each component. For example, if your bridge is made of components 0/3, 3/7, and 7/4, your bridge has a strength of 0+3 + 3+7 + 7+4 = 24.

For example, suppose you had the following components:

0/2
2/2
2/3
3/4
3/5
0/1
10/1
9/10

With them, you could make the following valid bridges:

  • 0/1
  • 0/110/1
  • 0/110/19/10
  • 0/2
  • 0/22/3
  • 0/22/33/4
  • 0/22/33/5
  • 0/22/2
  • 0/22/22/3
  • 0/22/22/33/4
  • 0/22/22/33/5

(Note how, as shown by 10/1, order of ports within a component doesn’t matter. However, you may only use each port on a component once.)

Of these bridges, the strongest one is 0/110/19/10; it has a strength of 0+1 + 1+10 + 10+9 = 31.

What is the strength of the strongest bridge you can make with the components you have available?

2.1.2 Solution

We solve this puzzle by backtracking with memoization to avoid recalculating knwon paths.

get_strongest_bridge <- function(pieces) {
  start <- keep(seq_along(pieces), \(i) any(pieces[[i]] == 0))
  memo <- new.env()
  n <- length(pieces)
  best_weight <- 0
  best_path <- NULL
  dfs <- function(current_val, used, path) {
    key <- paste(current_val, digest(used), sep = "_")
    if (exists(key, memo)) {
      return(memo[[key]])
    }
    
    max_weight <- sum(unlist(pieces[path]))
    max_path <- path
    
    for (idx in which(!used)) {
      piece <- pieces[[idx]]
      if (any(piece == current_val)) {
        next_val <- setdiff(piece, current_val)
        if (length(next_val) == 0) {
          ## double piece
          next_val <- current_val
        }
        next_used <- used
        next_used[idx] <- TRUE
        next_path <- c(path, idx)
        res_weight <- dfs(next_val, next_used, next_path)
        if (res_weight > max_weight) {
          max_weight <- res_weight
          max_path <- next_path
        }
      }
    }
    
    if (max_weight > best_weight) {
      best_weight <<- max_weight
      best_path <<- max_path
    }
    memo[[key]] <- max_weight
    max_weight
  }
  
  used <- rep(FALSE, n)
  
  for(si in start) {
    piece <- pieces[[si]]
    current_val <- setdiff(piece, 0L)
    if (length(current_val) == 0L) {
      current_val <- 0L
    }
    start_used <- used
    start_used[si] <- TRUE
    dfs(current_val, start_used, si)
  }
  best_weight
}
get_strongest_bridge(puzzle_data)
## [1] 2006

2.2 Part 2

2.2.1 Description

— Part Two —

The bridge you’ve built isn’t long enough; you can’t jump the rest of the way.

In the example above, there are two longest bridges:

  • 0/22/22/33/4
  • 0/22/22/33/5

Of them, the one which uses the 3/5 component is stronger; its strength is 0+2 + 2+2 + 2+3 + 3+5 = 19.

What is the strength of the longest bridge you can make? If you can make multiple bridges of the longest length, pick the strongest one.

2.2.2 Solution

We use the same approach as before replacing weight by length as the optimization criterion. In case there is a tie for the length, we use the weight as a tie-breaker.

get_weight_of_longest_bridge <- function(pieces) {
  start <- keep(seq_along(pieces), \(i) any(pieces[[i]] == 0))
  memo <- new.env()
  n <- length(pieces)
  best_length <- 0
  best_path <- NULL
  dfs <- function(current_val, used, path) {
    key <- paste(current_val, digest(used), sep = "_")
    if (exists(key, memo)) {
      return(memo[[key]])
    }
    
    max_length <- length(path)
    max_path <- path
    
    for (idx in which(!used)) {
      piece <- pieces[[idx]]
      if (any(piece == current_val)) {
        next_val <- setdiff(piece, current_val)
        if (length(next_val) == 0) {
          ## double piece
          next_val <- current_val
        }
        next_used <- used
        next_used[idx] <- TRUE
        next_path <- c(path, idx)
        res_length <- dfs(next_val, next_used, next_path)
        if (res_length > max_length) {
          max_length <- res_length
          max_path <- next_path
        } else if (res_length == max_length) {
          old_weight <- sum(unlist(pieces[max_path]))
          new_weight <- sum(unlist(pieces[next_path]))
          if (new_weight > old_weight) {
            max_length <- res_length
            max_path <- next_path
          }
        }
      }
    }
    if (max_length > best_length) {
      best_length <<- max_length
      best_path <<- max_path
    } else if (max_length == best_length) {
      old_weight <- sum(unlist(pieces[best_path]))
      new_weight <- sum(unlist(pieces[max_path]))
      if (new_weight > old_weight) {
        best_length <<- max_length
        best_path <<- max_path
      }
    }
    memo[[key]] <- max_length
    max_length
  }
  
  used <- rep(FALSE, n)
  
  for(si in start) {
    piece <- pieces[[si]]
    current_val <- setdiff(piece, 0L)
    if (length(current_val) == 0L) {
      current_val <- 0L
    }
    start_used <- used
    start_used[si] <- TRUE
    dfs(current_val, start_used, si)
  }
  sum(unlist(pieces[best_path]))
}
get_weight_of_longest_bridge(puzzle_data)
## [1] 1994