Next Composition of n into k parts - does anyone have a working algorithm?
What you are attempting to list is called an k-multicombination. The problem is often stated this way: given n indistinguishable balls and k boxes, list all possible ways to distribute all of the balls in the boxes. The number of such distributions is:
factorial(n + k - 1) / (factorial(k - 1) * factorial(n))
For further background, see Method 4 of the Twelve-Fold Way.
Here is the code to enumerate the distributions (C++):
string & ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut = string ( ), string strBuild = string ( ))
{
unsigned au4;
if (au4Boxes > 1) for (au4 = 0; au4 <= au4Balls; au4++)
{
stringstream ss;
ss << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls - au4;
ListMultisets (au4Boxes - 1, au4, strOut, ss.str ( ));
}
else
{
stringstream ss;
ss << "(" << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls << ")\n";
strOut += ss.str ( );
}
return strOut;
}
int main(int argc, char * [])
{
cout << endl << ListMultisets (3, 5) << endl;
return 0;
}
Here is the output from the above program (5 balls distributed over three boxes):
(5,0,0)
(4,1,0)
(4,0,1)
(3,2,0)
(3,1,1)
(3,0,2)
(2,3,0)
(2,2,1)
(2,1,2)
(2,0,3)
(1,4,0)
(1,3,1)
(1,2,2)
(1,1,3)
(1,0,4)
(0,5,0)
(0,4,1)
(0,3,2)
(0,2,3)
(0,1,4)
(0,0,5)
Since it took me a bit of effort to read the intention of the other c++ solution here a translation to python (also as generator result instead of string):
def weak_compositions(boxes, balls, parent=tuple()):
if boxes > 1:
for i in xrange(balls + 1):
for x in weak_compositions(boxes - 1, i, parent + (balls - i,)):
yield x
else:
yield parent + (balls,)
test:
>>> for x in weak_compositions(3, 5): print x
(5, 0, 0)
(4, 1, 0)
(4, 0, 1)
(3, 2, 0)
...
(0, 1, 4)
(0, 0, 5)