RobinHankin / permutations

https://robinhankin.github.io/permutations/
5 stars 3 forks source link

enumerate all *set* partitions of a given "shape" #41

Closed RobinHankin closed 1 year ago

RobinHankin commented 1 year ago

Suppose I want to list all partitions of a set of 5 elements into sets of size 2,2,1:

 setparts(c(a=2,b=2,c=1))

[1,] 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3
[2,] 2 2 3 1 1 1 2 2 3 2 2 3 1 1 1
[3,] 3 2 2 3 2 2 1 1 1 3 2 2 2 1 2
[4,] 2 3 2 2 3 2 3 2 2 1 1 1 2 2 1
[5,] 1 1 1 2 2 3 2 3 2 2 3 2 1 2 2
> 

But this is not very clear. We can use listParts()

 listParts(c(2,2,1))
[[1]]
[1] (1,5)(2,4)(3)

...
[snip]
...

[[15]]
[1] (2,4)(3,5)(1)

But above we see a list, which is not particularly easy to use. But how about this:

 restrictedsetparts <- function (v) {
    out <- as.partition(apply(setparts(v), 2, function(x) {
        c(split(seq_along(x), x), recursive = TRUE)
    }))
    rownames(out) <- rep(names(v), v)
    return(out)
}

restrictedsetparts(c(a=1,b=2,c=2))

a 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2
b 5 5 5 2 2 2 3 3 3 4 4 4 5 3 4
b 2 2 3 4 3 3 2 2 4 2 2 3 3 4 3
c 4 3 4 5 5 4 5 4 5 5 3 5 4 5 5
c 3 4 2 3 4 5 4 5 2 3 5 2 1 1 1

which is much more readily interpretable. The last column, for example, shows partition $\left\lbrace2,4\right\rbrace\left\lbrace3,5\right\rbrace\left\lbrace1\right\rbrace$. Note the absence of $\left\lbrace4,2\right\rbrace\left\lbrace3,5\right\rbrace\left\lbrace1\right\rbrace$ and $\left\lbrace3,5\right\rbrace\left\lbrace2,4\right\rbrace\left\lbrace1\right\rbrace$: the two boxes of size 2 are indistinguishable. It would be good to implement this in the package, although we must take care not to break setparts(5). Compare multinomial():

> multinomial(c(a=2,b=2,c=1))

a 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 3 3 4 3 3 4 2 2 2 3 3 4
a 2 2 2 3 3 4 5 4 5 3 4 5 3 3 4 5 4 5 4 5 5 4 5 5 3 4 5 4 5 5
b 3 3 4 2 2 2 2 2 2 4 3 3 1 1 1 1 1 1 1 1 1 1 1 1 4 3 3 2 2 2
b 4 5 5 4 5 3 3 5 4 5 5 4 4 5 3 3 5 4 2 2 2 5 4 3 5 5 4 5 4 3
c 5 4 3 5 4 5 4 3 3 2 2 2 5 4 5 4 3 3 5 4 3 2 2 2 1 1 1 1 1 1

Here we see $\left\lbrace1,2\right\rbrace\left\lbrace3,4\right\rbrace\left\lbrace5\right\rbrace$ and $\left\lbrace3,4\right\rbrace\left\lbrace1,2\right\rbrace\left\lbrace5\right\rbrace$: multinomial() considers the two boxes of size 2 to be distinguishable.

RobinHankin commented 1 year ago

got confused, this should be in the partitions package, not here in the permutations package.