Advent of Code: Day 15

1 minute read

I found the int_to_bin function on StackOverflow as my initial attempts didn’t quite work. Given the high number of iterations I tried to optimize things a little. After a few tests, vapply was faster than sapply or purrr::map_chr (I didn’t save the benchmarks). Not by much, but with over 40 millions elements, it was worth using it. I also use the parallel package to do the conversion into binary on each “generator” to speed up the process a little. On my laptop, the first problem took about 20 minutes to complete and the second a little less.

Part 1

library(parallel)

int_to_bin <- function(x) {
    paste(vapply(strsplit(paste(rev(intToBits(x))),""), `[[`,
                 character(1), 2)[17:32],
          collapse="")
}

next_row <- function(x, y = 16807) {
    (x * y) %% 2147483647
}


build_vec <- function(start, total_length, f) {
    vec <- integer(total_length+1)
    vec[1] <- start
    for (i in 2:(total_length+1)) {
        vec[i] <- next_row(vec[i-1], f)
    }
    vec[-1]
}

genA <- build_vec(516, 40e6, 16807)
genB <- build_vec(190, 40e6, 48271)

res <- mclapply(list(genA, genB),
                function(x) vapply(x, int_to_bin, character(1)))

sum(res[[1]] == res[[2]])

Part 2

build_vec2 <- function(start, total_length, f, multiple) {
    vec <- integer(total_length+1)
    vec[1] <- start
    for (i in 2:(total_length+1)) {
        res <- next_row(vec[i-1], f)
        while (res %% multiple != 0)
            res <- next_row(res, f)
        vec[i] <- res
    }
    vec[-1]
}


genA2 <- build_vec2(516, 5e6, 16807, 4)
genB2 <- build_vec2(190, 5e6, 48271, 8)

res2 <- mclapply(list(genA2, genB2),
                function(x) vapply(x, int_to_bin, character(1)))

sum(res2[[1]] == res2[[2]])

Comments