Enumeration of combinations of N balls in A boxes?

后端 未结 8 939
后悔当初
后悔当初 2020-12-30 18:06

I want to enumerate all possible combinations of N balls in A boxes.

example: I have 8

相关标签:
8条回答
  • 2020-12-30 19:07

    It is good idea to use python generator, as it was done above but here is more straightforward (not sure about efficency) version:

    def balls_in_baskets(balls=1, baskets=1):
        if baskets == 1:
            yield [balls]
        elif balls == 0:
            yield [0]*baskets
        else:
            for i in xrange(balls+1):
                for j in balls_in_baskets(balls-i, 1):
                    for k in balls_in_baskets(i, baskets-1):
                        yield j+k
    
    for i in balls_in_baskets(8,3):
        print i
    
    0 讨论(0)
  • 2020-12-30 19:09

    This works just fine starting with python 2.6, (2.5-friendly implementation of itertools.permutations is available as well):

    >>> import itertools
    >>> boxes = 3
    >>> balls = 8
    >>> rng = list(range(balls + 1)) * boxes
    >>> set(i for i in itertools.permutations(rng, boxes) if sum(i) == balls)
    {(0, 1, 7), (3, 1, 4), (0, 4, 4), (1, 0, 7), (4, 0, 4), (3, 0, 5), (1, 2, 5), (1, 7, 0), (0, 8, 0), (1, 4, 3), (6, 0, 2), (4, 3, 1), (3, 3, 2), (0, 5, 3), (5, 3, 0), (5, 1, 2), (2, 4, 2), (4, 4, 0), (3, 2, 3), (7, 1, 0), (5, 2, 1), (0, 6, 2), (6, 1, 1), (2, 2, 4), (1, 1, 6), (0, 2, 6), (7, 0, 1), (2, 1, 5), (0, 0, 8), (2, 0, 6), (2, 6, 0), (5, 0, 3), (2, 5, 1), (1, 6, 1), (8, 0, 0), (4, 1, 3), (6, 2, 0), (3, 5, 0), (0, 3, 5), (4, 2, 2), (1, 3, 4), (0, 7, 1), (1, 5, 2), (2, 3, 3), (3, 4, 1)}
    
    0 讨论(0)
提交回复
热议问题