首页 > 解决方案 > 从数字的分区生成排列

问题描述

我将生成一个分区的排列。我使用以下代码生成分区: library(partitions)

x <- c(2,4,6)       
parts <- listParts(length(x))
out <- rapply(parts, function(ii) x[ii], how="replace") 

并生成

出去

[[1]]
[1] (2,4,6)

[[2]]
[1] (2,6)(4)

[[3]]
[1] (2,4)(6)

[[4]]
[1] (4,6)(2)

[[5]]
[1] (2)(4)(6)

以一个元素为例,[1](2)(4)(6)我会生成所有可能的排列。我试过:

 library(combinat)
 permn(x)

但返回元素与输入的形式不同,例如元素 [1](21,33,41,40,39,3,6)(13,37) 返回:

[[1]]
[[1]]$`1`
[1] 21 33 41 40 39  3  6

[[1]]$`2`
[1] 13 37


[[2]]
[[2]]$`2`
[1] 13 37

[[2]]$`1`
[1] 21 33 41 40 39  3  6

几周前我做了类似的问题,但是在生成分区时给出的解决方案会为所有可能的分区生成排列,但是对于效率问题我不能使用它。解决方案就是这样:

library(partitions)
permListParts <- function (x) 
{
    f <- function(pp) {
        out <- split(seq_along(pp), pp)
        myPerms <- perms(length(out))
        apply(myPerms, 2, function(x) {
            temp <- out[x]
            class(temp) <- c(class(temp), "equivalence")
            temp
        })
    }
    apply(setparts(x), 2, f)}

标签: rlistpermutationpartition

解决方案


推荐阅读