【问题标题】:R: efficient computation of permutations of partitionsR:分区排列的有效计算
【发布时间】:2016-06-30 13:46:46
【问题描述】:

给定一个包含 n 唯一元素的向量:

x <- c('a','b','c')

我想为任意n 找到x 的所有分区的所有排列。对于n=3,这意味着 13 个订单:

('a', 'b', 'c')
('a') ('b','c')
('b','c') ('a')
('a','b') ('c')
('a','c') ('b')
('b') ('a','c')
('c') ('b','a')
('a') ('b') ('c')
('a') ('c') ('b')
('b') ('a') ('c')
('b') ('c') ('a')
('c') ('a') ('b')
('c') ('b') ('a')

可以使用partitions 库中的listParts 找到分区(不幸的是,setparts 似乎与最新版本的 R 不兼容),以及来自combinat 包的permn 的排列:

library(partitions)
library(combinat)
parts <- listParts(length(x))

p1 <- permn(parts[[1]])
p2 <- permn(parts[[2]])
...

但是,我很难找到一种有效的方法来置换分区和存储结果。我的目标是将结果映射到类似

的结构
  a b c
1 1 1 1
2 1 2 2
3 2 1 1
4 1 1 2 
...

其中整数表示排列中元素的顺序。由于分区在内部是无序的,因此分区中的任何元素都将获得相同的整数等级。似乎应该有某种方法可以通过引用分区的列表索引来有效地做到这一点,但我无法找出一种方法来做到这一点。

【问题讨论】:

  • 原来这个数量有自己的称谓,Fubini 数 (oeis.org/A000670),可以在 R 中使用 sum(factorial(unlist(lapply(partitions::listParts(n), length)))) 快速找到一组 n 元素

标签: r algorithm permutation partitioning


【解决方案1】:

这是一个简短的 sn-p,它将给出预期的结果:

x <- c('a','b','c')

## Probably not a good idea to name this parts as there
## is a function in the partitions package called parts
myParts <- partitions::listParts(length(x))

permParts <- unlist(lapply(seq_along(x), function(j) {
    tempParts <- myParts[lengths(myParts) == j]
    perms <- combinat::permn(j)

    unlist(lapply(tempParts, function(p) {
        lapply(perms, function(q) {
            t <- lapply(p[q], function(i) x[i])
            class(t) <- c("list", "equivalence")
            t
        })
    }), recursive = F)
}), recursive = F)

这是给定示例的输出:

permParts
[[1]]
[1] (a,b,c)

[[2]]
[1] (a,c)(b)

[[3]]
[1] (b)(a,c)

[[4]]
[1] (a,b)(c)

[[5]]
[1] (c)(a,b)

[[6]]
[1] (b,c)(a)

[[7]]
[1] (a)(b,c)

[[8]]
[1] (a)(b)(c)

[[9]]
[1] (a)(c)(b)

[[10]]
[1] (c)(a)(b)

[[11]]
[1] (c)(b)(a)

[[12]]
[1] (b)(c)(a)

[[13]]
[1] (b)(a)(c)

我不会说上述方法一定是最有效的解决方案,但如果不滚动您的算法,我想不出更有效的攻击。

【讨论】:

  • 谢谢!这与我最终提出的解决方案相关,但比我最终提出的解决方案更有效,后者涉及迭代地附加一个列表,而不是unlistlapply 的更有效组合。
猜你喜欢
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 2011-02-26
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多