views:

367

answers:

2

In cases where order does matter, it's rather easy to generate the matrix of all possible outcomes. One way for doing this is using expand.grid as shown here.

What if it doesn't?

If I'm right, the number of possible combinations is (S+N-1)!/S!(N-1)!, where S is the number of dice, each with N sides numbered 1 through N. (It is different from the well known combinations formula because it is possible for the same number to appear on more than one dice). For example, when throwing four six-sided dice, N=6 and S=4, so the number of possible combinations is (4+6-1)!/4!(6-1)! = 9!/4!x5! = 126. How can I generate a matrix of these 126 possible outcomes?

Thank you.

+1  A: 

Generaly you need to order each outcome from original expand.grid and then unique them, for example using apply:

X <- expand.grid(1:6,1:6,1:6,1:6)
dim(unique(t(apply(X,1,sort))))
#[1] 126   4

But you can be tricky and choose subset of all outcomes that are ordered:

X <- expand.grid(1:6,1:6,1:6,1:6)
dim(subset(X, Var1>=Var2 & Var2>=Var3 & Var3>=Var4))
# [1] 126   4

Second version is much faster.

Marek
+1 very smart answer!
nico
+3  A: 
Moron
@Moron You are right!. I posted before reading your answer, noticing that there was not code in it. No doubt you answered first, so I'm adding my code as a comment to your answer.S <- 6N <- 4n <- choose(S+N-1,N)outcomes <- t(apply(combn(S+N-1,N),2,sort)) - matrix(rep(c(0:(N-1)),each=n),nrow=n)
gd047
@gd047. Ok, I have edited my answer to add your code. Feel free to edit the answer if you feel it needs anything.
Moron
This is very comprehensive answer. One tip to the code: `combn` can apply a function to each combination, so `apply(combn(S+N-1,N),2,sort)` could be replaced with `combn(S+N-1,N,sort)`.
Marek