Search code examples
pythonuniquepermutationdice

Get sublist of n elements from unique permutations of a list


I'm writing code to roll dice with different numbers of sides together. The main function takes in a list of 2 numbers which represent the number of sides the dice have, e.g. [4, 6] — meaning the program will do things with a d4 and a d6.

Here's the problem:

I have a list of all the different types of dice to use [4, 6, 8, 10, 12, 20] and I need some code to figure out every unique group of 2 dice to pass in, without passing in the same dice in a different order, e.g.: don't pass in both [4, 6] and [6, 4].

I plan to expand the program in the future to roll n dice at a time, e.g. 5d4 and 2d20 so code that doesn't only work for 2 dice would be greatly appreciated.

Lastly, I want to be able to roll 2 of the same dice, e.g.: [4, 4].

If the problem needs more explaining, please let me know.


Solution

  • Use the combinations_with_replacements from itertools library.

    from itertools import combinations_with_replacement
    
    dice = [4, 6, 8, 10, 12, 20]
    N_dice = 2
    
    print(list(combinations_with_replacement(dice, N_dice)))
    

    Gives output

    [(4, 4), (4, 6), (4, 8), (4, 10), (4, 12), (4, 20), (6, 6), (6, 8), (6, 10), (6, 12), (6, 20), (8, 8), (8, 10), (8, 12), (8, 20), (10, 10), (10, 12), (10, 20), (12, 12), (12, 20), (20, 20)]