Let's say we have a set with n
elements. I want to iterate efficiently over all subsets with k
elements, such that during iteration, the elements are selected roughly equally.
Example
We have 7 elements: [a,b,c,d,e,f,g]
and we want all 4-subsets. There are overall binom(7)(4)
subsets.
- iteration:
[a,b,c,d]
- iteration:
[e,f,g,a]
(now each element was selected at least once) - iteration:
[b,c,d,e]
- iteration:
[f,g,a,b]
(now each element was selected at least twice) - iteration:
...
This only works, if n
is prime. It does not work with n = 6
and k = 3
.
I need an algorithm to get ALL possible subsets without generating them beforehand (for binom(30)(15)
we already have over 150 million subsets).
(I want to implement this with javascript, but any suggestion is welcome.)