给定一个整数K
和一个维度d
,如何获得具有length(alpha)的所有多索引
和 R 中的 alpha
= dsum(alpha) = K
?
示例:对于 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)
最佳答案
根据描述,在rep
插入列表之后,我们可以在从'0'到'k'的序列上使用
expand.grid
code> 'd' 次,然后过滤
仅 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)
RcppAlgos 中还有一个基于约束的组合函数
f2 <- function(k, d) {
out <- RcppAlgos::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 提到的,与 comboGeneral
相比,permuteGeneral
会更合适
k <- 3
d <- 2
permuteGeneral(0:k, d, TRUE, constraintFun = "sum",
comparisonFun = "==", limitConstraints = k)
或者使用组合
library(partitions)
asplit(compositions(k, d), 2)
关于r - 创建给定长度的所有多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71981319/