Last updated: 2017-12-28

Code version: 153a7d1

See more puzzles

Advent of Code

Session information

sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] bindrcpp_0.2           microbenchmark_1.4-2.1 aocodeR_0.1.1          testthat_1.0.2        
 [5] forcats_0.2.0          stringr_1.2.0          dplyr_0.7.4            purrr_0.2.4           
 [9] readr_1.1.1            tidyr_0.7.2            tibble_1.3.4           ggplot2_2.2.1.9000    
[13] tidyverse_1.2.1       

loaded via a namespace (and not attached):
 [1] zoo_1.8-0         reshape2_1.4.2    splines_3.4.2     haven_1.1.0       lattice_0.20-35  
 [6] colorspace_1.3-2  htmltools_0.3.6   yaml_2.1.15       base64enc_0.1-3   survival_2.41-3  
[11] rlang_0.1.4       foreign_0.8-69    glue_1.2.0        modelr_0.1.1      readxl_1.0.0     
[16] multcomp_1.4-8    bindr_0.1         plyr_1.8.4        munsell_0.4.3     gtable_0.2.0     
[21] cellranger_1.1.0  rvest_0.3.2       mvtnorm_1.0-6     codetools_0.2-15  psych_1.7.8      
[26] evaluate_0.10.1   knitr_1.17        parallel_3.4.2    curl_3.0          TH.data_1.0-8    
[31] broom_0.4.2       Rcpp_0.12.14      scales_0.5.0.9000 backports_1.1.1   jsonlite_1.5     
[36] mnormt_1.5-5      hms_0.4.0         digest_0.6.12     stringi_1.1.6     grid_3.4.2       
[41] rprojroot_1.2     cli_1.0.0         tools_3.4.2       sandwich_2.4-0    magrittr_1.5     
[46] lazyeval_0.2.1    crayon_1.3.4      pkgconfig_2.0.1   MASS_7.3-47       Matrix_1.2-12    
[51] rsconnect_0.8.5   xml2_1.1.1        lubridate_1.7.1   assertthat_0.2.0  rmarkdown_1.8    
[56] httr_1.3.1        rstudioapi_0.7    R6_2.2.2          nlme_3.1-131      git2r_0.19.0     
[61] compiler_3.4.2   

Brief

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/1--10/1
0/1--10/1--9/10
0/2
0/2--2/3
0/2--2/3--3/4
0/2--2/3--3/5
0/2--2/2
0/2--2/2--2/3
0/2--2/2--2/3--3/4
0/2--2/2--2/3--3/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/1–10/1–9/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?

Let’s go

Packages & functions

library(tidyverse)
library(testthat)
library(aocodeR)
options(stringsAsFactors = F)

Input

input <- aoc_get_input(day = 24, cookie_path = paste0(rprojroot::find_rstudio_root_file(),
                                                 "/secrets/session_cookie.txt")) 
input %>% head
[1] "14/42\n2/3\n6/44\n4/10\n23/49\n35/39\n46/46\n5/29\n13/20\n33/9\n24/50\n0/30\n9/10\n41/44\n35/50\n44/50\n5/11\n21/24\n7/39\n46/31\n38/38\n22/26\n8/9\n16/4\n23/39\n26/5\n40/40\n29/29\n5/20\n3/32\n42/11\n16/14\n27/49\n36/20\n18/39\n49/41\n16/6\n24/46\n44/48\n36/4\n6/6\n13/6\n42/12\n29/41\n39/39\n9/3\n30/2\n25/20\n15/6\n15/23\n28/40\n8/7\n26/23\n48/10\n28/28\n2/13\n48/14"

Benchmark

Because performance has been of such importance as Advent of Code ramped up and because I should probably know a lot more about Rs performance and be much better at testing it, I’m using the opportunity to start benchmarking some approaches (I’ll be going back, benchmarking and profiling the part 2s I’m stuck on due to terrible perfomance when I finish the puzzles I can first).

For this puzzle, I assumed finding which components match the next piece in the under construction bridge will liekly be the most important. So I tested a few approaches of storing and looking up the component element data, including an environment, a data.frame and a tibble. The test was to find the outlooking (ie will be looked up subsequently) element of the components that match the element (nxt) we are looking to connect.

I changed my approach later, stacking all individual elements of each component for easier search but, after checking the benchmarking results, chose to store everything in a data.frame because it’s fast enough but allows me to link the individual elements of a component to it’s key, something I wouldn’t be able to do in an environment hash table, without the kind of hack I was testing for in the benchmark (ie making unique names out of potential duplicate component element values). While trying to match values in an environment seems super slow too.

library(microbenchmark)

input <- input %>% strsplit(., "\n") %>% unlist %>% strsplit(., "/") %>% map(as.numeric)
e <- new.env(parent = emptyenv())
suppressMessages(map2(.x = map(input, 1) %>% make.names(unique = T), 
     .y = input, 
     .f = ~assign(.x, .y, envir = e)))
tbl <- tibble(inp = map_dbl(input, 1), out = map_dbl(input, 2))
df <- rbind(data.frame(port = map_dbl(input, 1), comps),
            data.frame(port = map_dbl(input, 2), comps))
#Let's search for everything with an input of 2
nxt <- 2
mbm = microbenchmark(
    env_key = map(mget(grep(paste0("X", nxt, "(\\.[0-9]*)?$"), 
                        names(e), value = T), envir = e), 2),
    env_value = unlist(mget(ls(e)[unlist(mget(ls(e), envir = e)) == nxt], envir = e)),
    tbl_base = tbl[tbl$inp == nxt, 2] %>% unlist,
    df_base = df[df$inp == nxt, 2],
    df_base_nm = df[df$inp == nxt, "out"],
    tbl_dplyr = tbl %>% filter(inp == nxt) %>% pull(out),
    times=50
)
summary(mbm) %>% arrange(mean)

Functions

When it came to the functions, I’m not gonna lie. I tried some pretty crazy stuff, thinking I might be able to sample enough from possible configurations to get the strongest bridge. I even trying to build some sort of weighting score for selecting the next piece but it was slow and didn’t work (I think AoC kicked me off at some point thinking I was just guessing! Well, I guess I was!)

It soon became clear that the most efficient way would be to just calculate all combos that run out of components to reuse. In the end, I’m actually quite pleased with what I came up, a function that recurses the search for a match to each of the matches in a call through lapply, finally assigning the bridge strength to a collecting environment when the recursion runs out of matches!

make_df <- function(input){
    input <- input %>% strsplit(., "\n") %>% unlist %>% strsplit(., "/") %>% map(as.numeric)
    comps <- paste0(map_dbl(input, 1), "/",  map_dbl(input, 2))
    rbind(data.frame(port = map_dbl(input, 1), comps),
          data.frame(port = map_dbl(input, 2), comps)) %>% 
        arrange(comps) %>% .[!duplicated(.),]
} 
build_bridges <- function(bridge.sf = NULL, port = 0, df, envir = bridges){
    avail <- df[df$port == port, "comps"] %>% .[!. %in% bridge.sf]
    
    if(length(avail) != 0){
        solid <- strsplit(avail, "/") %>% map_lgl(~.x[1] == .x[2])
        if(any(solid)){
            avail <- avail[solid]
        }else{
           port <- df[df$comps %in% avail & df$port != port, "port"] 
        }
        mapply(FUN = build_bridges, 
               bridge.sf = map(avail, ~c(bridge.sf, .x)),
               port = port,
               MoreArgs = list(df = df, envir = envir))
    }else{
        assign(paste0(bridge.sf, collapse = "-"), 
               eval(parse(text = paste0(gsub("/", "+", bridge.sf), collapse = "+"))),
               envir = envir)  
    }
}

Test

test_input <- "0/2\n2/2\n2/3\n3/4\n3/5\n0/1\n10/1\n9/10"
expect_equal({
    df <- make_df(test_input)
    test_bridges <- new.env(parent = emptyenv())
    build_bridges(bridge.sf = NULL, port = 0, df, envir = test_bridges)
    mget(ls(test_bridges), envir = test_bridges) %>% unlist %>% max},
    31)
mget(ls(test_bridges), envir = test_bridges)
$`0/1-10/1-9/10`
[1] 31

$`0/2-2/2-2/3-3/4`
[1] 18

$`0/2-2/2-2/3-3/5`
[1] 19

deploy

df <- make_df(input)
bridges <- new.env(parent = emptyenv())
build_bridges(bridge.sf = NULL, port = 0, df)

Success!



—- Part 2 —-

Brief

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/2--2/2--2/3--3/4
0/2--2/2--2/3--3/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.

Let’s go

Functions

Luckily, although I was pretty sure I was adding to the computational load, my dislike for non traceability paid off in the end and I was able to extract the lengths and strengths of the bridges from the full keys I had stored the strengths under without re-running anything.

bridge_length <- function(x){
    strsplit(x, "-") %>% unlist %>% length
}
get_longest_strength <- function(envir = bridges){
    lengths <- names(envir) %>% map_dbl(bridge_length)
    mget(names(envir), envir = envir)[lengths == max(lengths)] %>% unlist %>% max   
}

Test

expect_equal(get_longest_strength(test_bridges), 19)

deploy

get_longest_strength()
[1] 1673

Success!

via GIPHY



template based on the workflowr standalone template

LS0tCnRpdGxlOiAiLS0tIERheSAyNDogRWxlY3Ryb21hZ25ldGljIE1vYXQgLS0tIgphdXRob3I6ICJhbm5ha3J5c3RhbGxpIgpkYXRlOiAyMDE3LTEyLTI0Cm91dHB1dDogaHRtbF9ub3RlYm9vawplZGl0b3Jfb3B0aW9uczogCiAgY2h1bmtfb3V0cHV0X3R5cGU6IGlubGluZQotLS0KCmBgYHtyIGtuaXRyLW9wdHMtY2h1bmssIGluY2x1ZGU9RkFMU0V9CiMgVXBkYXRlIGtuaXRyIGNodW5rIG9wdGlvbnMKIyBodHRwczovL3lpaHVpLm5hbWUva25pdHIvb3B0aW9ucy8jY2h1bmstb3B0aW9ucwprbml0cjo6b3B0c19jaHVuayRzZXQoCiA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