Enumeration of combinations of N balls in A boxes?

后端 未结 8 1015
后悔当初
后悔当初 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 18:51

    You can define a recursive generator which creates a sub-generator for each 'for loop' which you wish to nest, like this:

    def ballsAndBoxes(balls, boxes, boxIndex=0, sumThusFar=0):
        if boxIndex < (boxes - 1):
            for counter in xrange(balls + 1 - sumThusFar):
                for rest in ballsAndBoxes(balls, boxes,
                                          boxIndex + 1,
                                          sumThusFar + counter):
                    yield (counter,) + rest
        else:
            yield (balls - sumThusFar,)
    

    When you call this at the top level, it will take only a 'balls' and 'boxes' argument, the others are there as defaults so that the recursive call can pass different things. It will yield tuples of integers (of length 'boxes') that are your values.

    To get the exact formatting you specified at the top of this post, you could call it something like this:

    BALLS = 8
    BOXES = 3
    print '\t',
    for box in xrange(1, BOXES + 1):
        print '\tbox_%d' % (box,),
    print
    for position, value in enumerate(ballsAndBoxes(BALLS, BOXES)):
        print 'case-%d\t\t%s' % (position + 1, 
                                 "\t".join((str(v) for v in value)))
    

提交回复
热议问题