Search code examples
pythonarrayslistdice

How to loop through an n-dimensional list and find all combinations


I wrote a program to roll some dice together. The way it works is I pass in the dice I want to roll to the main function, [4, 6] aka 4 sided dice and 6 sided dice. The program then generates 2 lists that contain all the possible outcomes for the dice individually

[1, 2, 3, 4, 5, 6] and [1, 2, 3, 4]

Then, I make a list of all possible outcomes and just add every combination of data between the two lists. Here's my code

#list of outcomes from current dice rolling - to contain sublists within it for each dice
rawDiceOutcomes = []

#list of total outcomes to find probabilities in
finalOutcomes = []

#generate n lists of outcomes 
for i in range(len(dice)):
    rawDiceOutcomes.append([i for i in range(1, dice[i]+1)])    #[1, 2, 3, 4], [1, 2, 3, 4, 5, 6] etc


#TODO : Figure out some way to do this for an n-dimensional list
for x in rawDiceOutcomes[0]:   
    for y in rawDiceOutcomes[1]:
        tempOutcome = x + y
        finalOutcomes.append(tempOutcome)

As the commentary shows, I know how to do this if only rolling 2 dice, but eventually, I want to be able to pass in 3, 4, 100 dice etc. How would I go about looping through all the lists so that I can pass in any number of dice and it works?


Solution

  • For a general approach with any dice:

    from itertools import product
    
    dice = [4, 6]
    
    individual_outcomes = [range(1, d+1) for d in dice]
    
    combined_outcomes = [*map(sum, product(*individual_outcomes))]