Given an array such as the following
$array = ('1', '2', '3', '4', '5', '6', '7');
I'm looking for a method to generate all possible combinations, with a minimum number of elements required in each combination r. (eg if r = 5 then it will return all possible combinations containing at least 5 elements)
A combination can be expressed as
First, we determine
$n
as the number of elements in the array. And$r
is the minimum number of elements in each combination.Next, we determine
$max
as the maximum number that can be represented by$n
binary digits. That is, if$n = 3
, then$max = (111)
2= 7
. To do this, we first create a empty string$maxBinary
and add$n
number of1
s to it. We then convert it to decimal, and store it in$max
.Then, we list out every binary number from
0
to$max
and store those that have more than$r
number of1
s in them.Then, we use the same trick as above to select elements for our combination. I believe the comments explain enough.
And that is it. You are done!
Now if you have something like
then it would give you
29
.Additional notes:
I read up on this only after seeing your question, and as a newcomer, I found these useful:
Also, here are some quick links to the docs, that should help people who see this in the future:
Combinations of
k
out ofn
items can be defined recursively using the following function:The above is based on the recursive definition that to choose
k
outn
elements, one can fix an elementx
in the list, and there areC(k-1, xs\{x})
combinations that containx
(i.e.res1
), andC(k,xs\{xs})
combinations that do not containx
(i.e.res2
in code).Full example: