Created
December 14, 2020 15:35
-
-
Save dirkschumacher/207f882a3511703f18fde359d70baed8 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
input <- readLines("path/to/input") | |
input <- as.integer(input) | |
library(ompr) | |
library(ompr.roi) | |
library(ROI.plugin.glpk) | |
library(tidyverse) | |
n <- length(input) | |
MIPModel() %>% | |
# a variable for each input number | |
add_variable(y[i], type = "binary", i = 1:n) %>% | |
set_objective(0) %>% | |
# we want to select exactly two numbers | |
add_constraint(sum_expr(y[i], i = 1:n) == 2) %>% | |
# the sum of the two selected numbers should be 2020 | |
add_constraint(sum_expr(input[i] * y[i], i = 1:n) == 2020) %>% | |
solve_model(with_ROI("glpk", verbose = FALSE)) %>% | |
get_solution(y[i]) %>% | |
filter(value == 1) %>% | |
pull(i) -> indexes | |
sum(input[indexes]) | |
#> [1] 2020 | |
prod(input[indexes]) | |
#> [1] 357504 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment