Generating permutations with a sum constraint

拥有回忆 提交于 2019-12-04 08:21:05

I think what you're asking for is pretty shoe-horn specific and unlikely to be "easy to implement" (efficiently). A different way to look at it is to do the conditioning as you run the experiment (assuming this is a design for trials).

I wrote a lazyExpandGrid.R that is similar in concept to a lazy expand.grid, meaning it does not evaluate all possible combinations up front. The code can be inserted later in this answer if needed, but the github-gist is fairly solid (and not short).

Using it, you should be able to do:

set1 <- c(10, 15, 20)
set2 <- c(8, 9)
set3 <- c(1, 2, 3, 4)

iter <- lazyExpandGrid(set1, set2, set3)

while (is.data.frame(item <- iter$nextItem())) {
  p <- sum(item)
  if (p < 25 || 29 < p) next
  print(item) # but really, do something more interesting here
}
#   Var1 Var2 Var3
# 3   20    8    1
#   Var1 Var2 Var3
# 5   15    9    1
#   Var1 Var2 Var3
# 8   15    8    2
#    Var1 Var2 Var3
# 11   15    9    2
#    Var1 Var2 Var3
# 14   15    8    3
#    Var1 Var2 Var3
# 17   15    9    3
#    Var1 Var2 Var3
# 20   15    8    4
#    Var1 Var2 Var3
# 23   15    9    4

Caveat emptor: the function is mostly usable, but there are certainly ways it can be improved. For instance, the use of is.data.frame(item <- iter$nextItem()) is effectively an isTruthy test (name from shiny); currently it returns a 1-row data.frame until nothing remains, then returns FALSE. As I look at it now, that can most certainly be improved, I just haven't had the need. Feel free to comment on the github gist page if you have thoughts, bugs, etc.

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