13: Claw Contraption

library(mistlecode)

options(scipen = 999)

Figuring out how best to parse the input was annoying. I need to remember that tidyr::extract() exists.

.get_buttons <- function(x) {
  x <-
    stringr::str_match(x$raw, '(\\d+), Y[+=](\\d+)')[,-1] |>
    mistlecode::cast_matrix(as.integer)
  if (all(is.na(x[1,]))) x[-1,] else x
}
dt <-
  'input.txt' |>
  readLines() |>
  tibble::tibble() |>
  setNames('raw') |>
  dplyr::mutate(
    'game' = cumsum(.data$raw == '')
  ) |>
  tidyr::nest('data' = raw) |>
  dplyr::pull(.data$data) |>
  purrr::map(\(x) {
    x <- .get_buttons(x)
    list('a' = x[1,], 'b' = x[2,], 'p' = x[3,])
  })

Part 1

I got to do math!!! I’m so proud of myself for this one. Like genuinely actually for realizing I could just math it out. And my solution is so fast too! I probably could’ve done the linear programming, but just solving seemed easier?

ixa+jxb=X,iya+jyb=Yixa=Xjxb,iya=Yjybi=Xjxbxa,i=YjybyaXjxbxa=YjybyaXjxb=xaYjxaybyayaXjxbya=xaYjxaybjxbya+jxayb=xaYyaXj(xbya+xayb)=xaYyaXj=xaYyaXxaybxbya

dt |>
  purrr::map(\(x) {
    j <-
      ((x$a[1] * x$p[2]) - (x$a[2] * x$p[1])) / 
      ((x$a[1] * x$b[2]) - (x$b[1] * x$a[2]))
    i <- (x$p[1] - (j * x$b[1])) / x$a[1]
    x <- c(i * 3, j * 1)
    if (all(as.integer(x) == x)) sum(x)
  }) |>
  purrr::discard(is.null) |>
  unlist() |> 
  sum()
[1] 33921

Part 2

This was supremely unsatisfying. I kept multiplying by 10000000000000 instead of adding then for whatever reason if I leave my if statement as an all(x) kinda deal, it doesn’t work right. I spent way too long on random bit64 stuff and trying to solve to get rid of the 10000000000000.

dt |>
  purrr::map(\(x) {
    x$p <- x$p + 10000000000000
    j <-
      ((x$a[1] * x$p[2]) - (x$a[2] * x$p[1])) / 
      ((x$a[1] * x$b[2]) - (x$b[1] * x$a[2]))
    if (j < 0 || j %% 1 != 0) return(NULL)
    i <- (x$p[1] - (j * x$b[1])) / x$a[1]
    if (i < 0 || i %% 1 != 0) return(NULL)
    x <- c(i * 3, j * 1)
    sum(x)
  }) |>
  purrr::discard(is.null) |>
  unlist() |> 
  sum()
[1] 82261957837868