Update: bah, that crafty tye previously posted essentially the same iterator...
I wrote up this iterator a while ago for some now-long-forgotten purpose. I just found it laying around, so I thought I should post it..
An integer partition of n is a set of positive integers which adds up to n. For instance, the
integer partitions of 5 are:
5, 4+1, 3+2, 3+1+1, 2+2+1, 2+1+1+1, 1+1+1+1+1
Note that we do not care about the order of terms in the addition.
This iterator generates all the integer partitions of a given number. It's an implementation of the very simple algorithm from this paper.
It has the nice feature that it is memoryless -- that is, it is not a closure which keeps internal state. To get the next partition in the sequence, just pass in the previous one. In this sense, it is similar to tye's memoryless iterator for permutations.
This iterator outputs the partitions in reverse lexicographic order. Since the first partition of N in this ordering is just the singleton list containing N itself, all you have to do to start it up is call it with the single argument N. There is no real error checking built-in -- you have to call it with a list of positive integers.
Interesting. I needed to generate some integer partitions myself for something I was working on the other day and I was surprised to discover that there wasn't anything already available on CPAN.
I searched around, and ran across the same paper. I imemplented both algorithms proposed by Zoghbi and Stojmenovic in that paper, to permit forward and reverse lexicographic orderings and released it as a module.
My only comment is that while your code is very consice, I think you have removed the constant average delay property that the original algorithm features. The algorithm only requires two scalars to maintain state, so it's not as if its a memory pig.
• another intruder with the mooring in the heart of the Perl