Home > Software engineering >  How to loop through an n-dimensional list and find all combinations
How to loop through an n-dimensional list and find all combinations

Time:10-03

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?

CodePudding user response:

Use itertools.product to generate any combinations for any number of list:

import itertools

rawDiceOutcomes = [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]
res = [sum(comb) for comb in itertools.product(*rawDiceOutcomes)]
print(res)

Output

[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10]

The above code remains unchange for any length of rawDiceOutcomes.

CodePudding user response:

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))]
  • Related