Reputation: 155
I'm trying to find all possible partitions (including 0) of M into N parts using R. Then, I would like to permutate each outcome without replacement and without repeatition.
For example, for M=4 and N=2, I want to get:
[1,] 4 3 2 0 1
[2,] 0 1 2 4 3
Now, I can get:
[1,] 4 3 2
[2,] 0 1 2
using partitions::restrictedparts(4, 2, include.zero=TRUE)
. How should I continue?
To give some background of this question, I'm actually trying to find all possible outcomes of the number of occurence of each side after rolling a die for 60 times.
Upvotes: 2
Views: 154
Reputation: 7597
There is a function available in the package that you are currently using (i.e. partitions
) that does just what you are looking for. It is appropriately called compositions
(See Composition (combinatorics) for more information).
partitions::compositions(4, 2)
[1,] 4 3 2 1 0
[2,] 0 1 2 3 4
Now, to solve your actual problem, we have:
myParts <- partitions::compositions(60, 6) ## Note that include.zero is TRUE by default
dim(myParts)
[1] 6 8259888
And here is the output:
transMat <- t(as.matrix(myParts))
head(transMat)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 60 0 0 0 0 0
[2,] 59 1 0 0 0 0
[3,] 58 2 0 0 0 0
[4,] 57 3 0 0 0 0
[5,] 56 4 0 0 0 0
[6,] 55 5 0 0 0 0
tail(transMat)
[,1] [,2] [,3] [,4] [,5] [,6]
[8259883,] 1 0 0 0 0 59
[8259884,] 0 1 0 0 0 59
[8259885,] 0 0 1 0 0 59
[8259886,] 0 0 0 1 0 59
[8259887,] 0 0 0 0 1 59
[8259888,] 0 0 0 0 0 60
Upvotes: 2