I'm looking to figure out the formula for putting K balls in N urns, where each of the N urns has a specific max capacity. For example,
- Urn A has capacity for at most 5 balls
- Urn B has capacity for at most 2 balls
- Urn C has capacity for at most 1 ball
- Urn D has capacity for at most 2 balls
How many ways are there to put 5 indistinguishable balls in urns A, B, C and D?
With brute-force code, I know that this example has these 18 solutions:
(0, 2, 1, 2) (1, 1, 1, 2) (1, 2, 0, 2) (1, 2, 1, 1) (2, 0, 1, 2) (2, 1, 0, 2) (2, 1, 1, 1) (2, 2, 0, 1) (2, 2, 1, 0) (3, 0, 0, 2) (3, 0, 1, 1) (3, 1, 0, 1) (3, 1, 1, 0) (3, 2, 0, 0) (4, 0, 0, 1) (4, 0, 1, 0) (4, 1, 0, 0) (5, 0, 0, 0)
But I'm having trouble coming up with a general formula, which I need for my application, where the numbers get too large to brute-force like this. Does anyone know how to compute the number of combinations for putting indistinguishable balls in urns, only with max capacity for each urn?
After researching, and in particular looking at the answers to this post Number of ways to distribute indistinguishable balls into distinguishable boxes of given size and this post Using generating functions in combinatorics, I realize that @MathLover's comment above is right — thank you! Quoted here:
For those less interested in the pure formula than in the implementation, as I am, here's the code I'm now using: