给定一个整数K
和一个维数d
,如何得到R中length(alpha) = d
和sum(alpha) = K
的所有多索引alpha
?
例如:对于K=3
和d=2
,如果我们将多个索引组织在一个列表alphas
中,我们将得到
alphas[[1]] = c(3,0)
alphas[[2]] = c(2,1)
alphas[[3]] = c(1,2)
alphas[[4]] = c(0,3)
给定一个整数K
和一个维数d
,如何得到R中length(alpha) = d
和sum(alpha) = K
的所有多索引alpha
?
例如:对于K=3
和d=2
,如果我们将多个索引组织在一个列表alphas
中,我们将得到
alphas[[1]] = c(3,0)
alphas[[2]] = c(2,1)
alphas[[3]] = c(1,2)
alphas[[4]] = c(0,3)
根据描述,我们可以在从"0"到"k"的序列上使用expand.grid
,在rep
次重复list
次"d"之后,然后Filter
次仅使用sum
作为"k"的行
f1 <- function(k, d) {
lapply(Filter(function(x) sum(x) == k,
asplit(expand.grid(rep(list(0:k), d)), 1)), unname)
}
-测试
> f1(3, 2)
[[1]]
[1] 3 0
[[2]]
[1] 2 1
[[3]]
[1] 1 2
[[4]]
[1] 0 3
或者用rowSums
过滤会稍微快一点
d1 <- expand.grid(rep(list(0:3), 2))
asplit(unname(d1)[rowSums(d1) == 3,], 1)
还有一个基于约束的组合函数Rcpp算法s
f2 <- function(k, d) {
out <- Rcpp算法s::comboGeneral(0:k, d, constraintFun = "sum",
comparisonFun = "==", limitConstraints = k)
asplit(rbind(out, out[, ncol(out):1]), 1)
}
-测试
> f2(3, 2)
[[1]]
[1] 0 3
[[2]]
[1] 1 2
[[3]]
[1] 3 0
[[4]]
[1] 2 1
或者就像@JosephWood提到的,permuteGeneral
比comboGeneral
更合适
k <- 3
d <- 2
permuteGeneral(0:k, d, TRUE, constraintFun = "sum",
comparisonFun = "==", limitConstraints = k)
还是compositions
块
library(partitions)
asplit(compositions(k, d), 2)