I had a very similar problem a couple of years ago. how I eventually implemented this:
1. Store each set as a sorted array of element identifiers (no two identifiers are the same)
2. for iterating over subsets of a given size, N begin with 1 N elements of the original set
3. To move on to the next subset, you implement a kind of “clockwork” mechanism - take the last (highest identifier) of your subset and replace it with your neighbor in the subset (next higher identifier).
4. If the superset does not have such a higher neighbor, increase the next lower element of the subset, and then set the oldest memeber next for it.
steps 3 and 4 are recursive.
An example of a sequence of results for iterating over all triplets {1,2,3,4,5}:
{1,2,3} - 3 lowest memebers {1,2,4} - "increment" 3 to 4 {1,2,5} - 4 to 5 {1,3,4} - couldnt "increment" 5, so incremented 2-->3 and picked then next one as 3rd {1,3,5} - 4-->5 {1,4,5} - couldnt increment 5 ... {2,3,4} - couldnt increment 5, couldnt increment 4, incremented 1-->2 {2,3,5}
etc.
more complex than brand offer, but takes up less memory space and stack. its also “restartable” - this means that you can pass some subset to algo and it will be your “next” subset.
radai
source share