Created
December 10, 2025 10:13
-
-
Save tomjemmett/820a60057cba0857e5a6f5fe704ac11f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(lpSolve) | |
| solve_button_problem <- function(buttons, target, costs) { | |
| n_buttons <- nrow(buttons) | |
| n_positions <- ncol(buttons) | |
| constraints_matrix <- t(buttons) | |
| constraints_rhs <- target | |
| constraints_dir <- rep("=", n_positions) | |
| result <- lp( | |
| direction = "min", | |
| objective.in = costs, | |
| const.mat = constraints_matrix, | |
| const.dir = constraints_dir, | |
| const.rhs = constraints_rhs, | |
| all.int = TRUE | |
| ) | |
| result$objval | |
| } | |
| makeButton <- function(n, xs) { | |
| xs <- as.integer(xs) | |
| b <- integer(n) | |
| for (x in xs) { | |
| b[x + 1] <- 1 | |
| } | |
| b | |
| } | |
| solveLine <- function(line) { | |
| target <- stringr::str_extract(line, "(?<=\\{).*(?=\\})") |> | |
| stringr::str_split(",") |> | |
| _[[1]] |> | |
| as.integer() | |
| n <- length(target) | |
| buttons <- stringr::str_extract(line, "(?<=\\().*(?=\\))") |> | |
| stringr::str_split("\\) \\(") |> | |
| _[[1]] |> | |
| stringr::str_split(",") |> | |
| lapply(\(xs) makeButton(n, xs)) |> | |
| purrr::flatten_int() |> | |
| matrix(ncol = n, byrow = TRUE) | |
| costs <- replicate(nrow(buttons), 1) | |
| solve_button_problem(buttons, target, costs) | |
| } | |
| file <- readr::read_lines("inputs/actual/10.txt") | |
| sum(purrr::map_dbl(file, solveLine)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment