如何在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)
chinsoon12

您可以将其添加到约束中,如下所示:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章