如何为 R 中背包问题的线性规划添加约束?

How to add constraints to Linear Programming of the Knapsack Problem in R?

我正在研究在以下位置找到的代码:https://sites.math.washington.edu/~conroy/2015/m381-aut2015/Rexamples/knapsack.r

我想知道是否有人知道如何添加一个条件约束,只允许背包中有一定数量的物品。我如何修改代码以仍然优化背包的价值但只带一定数量的物品?

# import the lpsolve library
library(lpSolve)

# objective function
knapsack.obj <- c(500,300,100,210,360,180,220,140,90)

#constraints
knapsack.con <- matrix(c(30,35,10,15,35,22,29,18,11),nrow=1,byrow=TRUE)
knapsack.dir <- c("<=")
knapsack.rhs <- c(100)

#solve
# Note when we call the lp function, we set all.bin=TRUE to indicate that all variables are 0 or 1
# If we just wanted to specify integer values generally, we would set all.int=TRUE
# The default for both of these options if FALSE
knapsackSolution <- lp("max",knapsack.obj,knapsack.con,knapsack.dir,knapsack.rhs,all.bin=TRUE) 
print("Solution is:")
print(knapsackSolution$solution)
print("Objective function value at solution is:")
print(knapsackSolution$objval)

您可以按如下方式将其添加到约束中:

numItems <- 5
knapsack.con <- matrix(c(30,35,10,15,35,22,29,18,11, rep(1, length(knapsack.obj))), nrow=2, byrow=TRUE)
knapsack.dir <- c("<=", "==")
knapsack.rhs <- c(100, numItems)