I want to generate all the subsets of size k from a set.
eg:-say I have a set of 6 elements, I have to list all the subsets in which the cardinality of elements is 3
The most intuitive algorithm would indeed use recursion. When you have a set, we will assume you can iterate over all its elements.
If I call tail(e) a set of all the elements after element e.
Thus I want right now combinations(s,k)
loop over each element in s and get e :: combinations(tail(e), k-1) where :: means "concatenated to each of"
Of course sometimes there will be no such combinations (you are off the end of the list).
You just need a master collection (set of sets) to add your combinations to and a way to create
So assuming we have no globals anywhere we can have something like:
getCombinations( headset [in], tailset [in], count [in], output [append] )
headset or tailset could be empty. count could be 0, in which case we write "headset" to output (the base condition) otherwise we iterate through each element in tailset, adding it (locally) to headset, make tailset (locally) the tail of our element, subtract 1 from count and "recurse" by calling the function.