13: Claw Contraption
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?
\[\begin{gather*} ix_a + jx_b = X, iy_a + jy_b = Y\\ ix_a = X - jx_b, iy_a = Y - jy_b\\ i = \frac{X - jx_b}{x_a}, i = \frac{Y - jy_b}{y_a}\\ \frac{X - jx_b}{x_a} = \frac{Y - jy_b}{y_a}\\ X - jx_b =\frac{x_aY - jx_ay_b}{y_a}\\ y_aX - jx_by_a = x_aY - jx_ay_b\\ -jx_by_a + jx_ay_b = x_aY - y_aX\\ j * (-x_by_a + x_ay_b) = x_aY - y_aX\\ j = \frac{x_aY - y_aX}{x_ay_b - x_by_a} \end{gather*}\]
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