Calculate all the possible sums of rolling x die with y sides

Viewed 59

I'm writing a function that helps me calculate the possible outcomes of summing a variable numbe of die with a variable number of sides (for instance, the total sum of two six-sided die and a four sided die) and I've been stumped for a while.

Rolling two three sided die for instance should output an array with all 9 possible combinations:

[[1,1],
 [1,2], 
 [1,3],
 [2,1],
 (etc.)
 [3,2],
 [3,3]]

And I can't quite figure it out. I've managed to generate range to enumerate on, but I can't quite make it.

dice = [6,6]
diceRanges = [range(0, die) for die in dice]
diceIndex = [0 for die in dice]

outcomes = []

for idx, rng in enumerate(diceRanges):
    for var in rng:
        diceIndex[idx] = var
        outcomes.append([val for val in diceIndex])
        
outcomes

I've seen some things around but never quite as simple as it seems to be.

Cheers

2 Answers

It's simple if you use itertools:

import itertools

outcomes = list(itertools.product(*diceRanges))

Using numpy only

dice_sides = 6
dices_values = np.arange(1,dice_sides+1)
outcome =  np.dstack(np.meshgrid(dices_values, dices_values)).reshape(-1,2)

Out[313]:
array([[1, 1],
       [2, 1],
       [3, 1],
       [4, 1],
       [5, 1],
       [6, 1],
       [1, 2],
       [2, 2],
       [3, 2],
       [4, 2],
       [5, 2],
       [6, 2],
       [1, 3],
       [2, 3],
       [3, 3],
       [4, 3],
       [5, 3],
       [6, 3],
       [1, 4],
       [2, 4],
       [3, 4],
       [4, 4],
       [5, 4],
       [6, 4],
       [1, 5],
       [2, 5],
       [3, 5],
       [4, 5],
       [5, 5],
       [6, 5],
       [1, 6],
       [2, 6],
       [3, 6],
       [4, 6],
       [5, 6],
       [6, 6]])
Related