A Google search reveals plenty about generating all possible partitions of an integer n into m parts, but I haven’t found anything about sampling a uniformly distributed random partition of n into m parts.
A Google search reveals plenty about generating all possible partitions of an integer n
Share
Here is some code that does it. This is O(n2) the first time you call it, but it builds a cache so that subsequent calls are O(n).
How this works: We can calculate how many partitions of an integer n there are in O(n2) time. As a side effect, this produces a table of size O(n2) which we can then use to generate the kth partition of n, for any integer k, in O(n) time.
So let total = the number of partitions. Pick a random number k from 0 to total – 1. Generate the kth partition.