R lpsolve binary find all possible solutions

…衆ロ難τιáo~ 提交于 2019-11-27 08:15:42

问题


I have a linear programming problem. All variables are binary and I want to get all possible solutions.I know that I can set parameter num.bin.solns to provide multiple solutions. But is there any easy way to ask for all possible solutions?

For example in below case I know that the maximum number of answers is 6. But if I don't know the maximum possible solutions then how can I set the num.bin.solns parameter such that it would return all possible solutions?

library("lpSolve")
A=matrix (c(1,1,1,1), nrow=1, byrow=TRUE)
b=(2)
signs='=='
c_=rep(0,4)
res = lpSolve::lp('max', c_, A, signs, b,  all.bin = TRUE, num.bin.solns=6)

回答1:


Here's one way to do it. lpSove actually gives you the num.bin.solns that it finds, and you can access that using the $ notation.

You can initially set the num.bin.solns to be some large number (say 1000). And then access the mylp$num.bin.solns to get the exact value.

mylp <- lp('max', c_, A, signs, b,  all.bin = TRUE, num.bin.solns=1000)
numcols <- 4
numsols <- mylp$num.bin.solns

solutions <- matrix(head(mylp$solution, numcols*numsols), nrow=numsols, byrow=TRUE)

> numsols
[1] 6

And you can print out the individual solutions:

> solutions
     [,1] [,2] [,3] [,4]
[1,]    0    0    1    1
[2,]    0    1    0    1
[3,]    1    0    0    1
[4,]    1    0    1    0
[5,]    1    1    0    0
[6,]    0    1    1    0


来源:https://stackoverflow.com/questions/28666795/r-lpsolve-binary-find-all-possible-solutions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!