创建给定长度的所有多索引

发布于 2025-01-23 11:30:27 字数 366 浏览 0 评论 0 原文

给定一个整数 k 和一个尺寸 d ,我如何使用 length(alpha)= d alpha alpha /code>和 sum(alpha)= k in R?

示例:对于 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)

Given an integer K and a dimension d, how can I get all multi-indices alpha with length(alpha) = d and sum(alpha) = K in R?

Example: For K=3 and d=2 and if we organize the multi-indices in a list alphas we would get

alphas[[1]] = c(3,0)
alphas[[2]] = c(2,1)
alphas[[3]] = c(1,2)
alphas[[4]] = c(0,3)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梨涡少年 2025-01-30 11:30:27

基于描述,我们可以在 rep 许可 list> list '之后使用 expand.grid 在“ 0”到'k'的序列上使用' d'times,然后过滤仅具有 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)

}

-testing

> 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)

使用构图

library(partitions)
asplit(compositions(k, d), 2)

Based on the description, we may use expand.grid on the sequence from '0' to 'k', after replicating the list 'd' times, then Filter only the rows having the sum as 'k'

f1 <- function(k, d) { 
 lapply(Filter(function(x) sum(x) == k, 
      asplit(expand.grid(rep(list(0:k), d)), 1)), unname)

}

-testing

> f1(3, 2)
[[1]]
[1] 3 0

[[2]]
[1] 2 1

[[3]]
[1] 1 2

[[4]]
[1] 0 3

Or slightly more faster would be to filter with rowSums

d1 <- expand.grid(rep(list(0:3), 2))
asplit(unname(d1)[rowSums(d1) == 3,], 1)

There is also a constraints based combinations functions in RcppAlgos

f2 <- function(k, d) {

 out <- RcppAlgos::comboGeneral(0:k, d, constraintFun = "sum", 
      comparisonFun = "==", limitConstraints = k)
 asplit(rbind(out, out[, ncol(out):1]), 1)

}

-testing

> f2(3, 2)
[[1]]
[1] 0 3

[[2]]
[1] 1 2

[[3]]
[1] 3 0

[[4]]
[1] 2 1

Or as @JosephWood mentioned permuteGeneral would be more adequate compared to comboGeneral

k <- 3
d <- 2
permuteGeneral(0:k, d, TRUE, constraintFun = "sum",
  comparisonFun = "==", limitConstraints = k)

Or with compositions

library(partitions)
asplit(compositions(k, d), 2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文