Skip to content

Instantly share code, notes, and snippets.

@dirkschumacher
Created December 14, 2020 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirkschumacher/207f882a3511703f18fde359d70baed8 to your computer and use it in GitHub Desktop.
Save dirkschumacher/207f882a3511703f18fde359d70baed8 to your computer and use it in GitHub Desktop.
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