Determine items to include in a collection so that the total weight is less than or equal to a given limit and the total survival points is as large as possible
Maximize survivalpoints
subject to
totalweight < weightlimit
dataset <- data.frame(item = c("pocketknife", "beans", "potatoes", "unions",
"sleeping bag", "rope", "compass"), survivalpoints = c(10, 20, 15, 2, 30,
10, 30), weight = c(1, 5, 10, 1, 7, 5, 1))
dataset
## item survivalpoints weight
## 1 pocketknife 10 1
## 2 beans 20 5
## 3 potatoes 15 10
## 4 unions 2 1
## 5 sleeping bag 30 7
## 6 rope 10 5
## 7 compass 30 1
weightlimit <- 20
#install.packages("ompr")
#install.packages("ompr.roi")
library(ompr)
library(ompr.roi)
library(ROI)
library(ROI.plugin.glpk)
library(dplyr)
n <- 7 # length of x
model <- MIPModel()
model <- add_variable(model, x[i], i = 1:n, type = "binary")
model <- set_objective(model, sum_expr(dataset$survivalpoints[i] * x[i], i = 1:n) )
model <- add_constraint(model, sum_expr(dataset$weight[i] * x[i], i = 1:n) <= weightlimit )
model <- solve_model(model, with_ROI(solver = "glpk"))
get_solution(model, x[i])
## variable i value
## 1 x 1 1
## 2 x 2 1
## 3 x 3 0
## 4 x 4 1
## 5 x 5 1
## 6 x 6 1
## 7 x 7 1
reference: https://dirkschumacher.github.io/ompr/articles/modelling.html