输出带约束的组合的函数



我希望编写一个接受两个变量 n 和 k 的函数,其中 n>k,并返回由整数 k 组成的向量。该函数应返回所有可能的向量,其中 k 是向量中的最大数,向量中的所有元素总和为 n。简而言之,我想要完成的是以下内容:

n = 10, k = 3因此向量如下

(3,1,1,1,1,1,1,1)
(3,2,1,1,1,1,1)
(3,2,2,1,1,1)
(3,2,2,2,1)
(3,3,1,1,1,1)
(3,3,2,1,1)
(3,3,2,2)
(3,3,3,1)

你可以使用包 RcppAlgos 来实现这一点:

library(RcppAlgos)
n <- 10
k <- 3
#loop over 1:n
res <- lapply(seq_len(n), function(i) {
#generate all combinations of a vector with constraint
x <- comboGeneral(k, i, TRUE, constraintFun = "sum", 
comparisonFun = "==", 
limitConstraints = n)
#remove solutions that don't contain k
x[as.logical(rowSums(x == k)),]
})
res <- res[lengths(res) > 0]
res <- lapply(res, function(x) if (is.matrix(x)) asplit(x, 1) else x)
library(rlist)
list.flatten(res)
#[[1]]
#[1] 1 3 3 3
#
#[[2]]
#[1] 2 2 3 3
#
#[[3]]
#...

最新更新