Hello,
I'm trying to figure out a way to generate all the possible subsets of a given size from a given set of n elements. I've figured out that I can map all of the possible sets to the integers from 0 to 2^n, and use the binary representation to say whether a particular element is included or excluded. So for instance element1 corresponds to the least significant bit, ..., elementN corresponds to the most significant bit, and the element is either included or excluded based on whether that element corresponds to a bit value of 1 or 0.
For example, if the starting set has 6 elements, subset 5 = 000101 corresponds to a subset of size 2 with element1 and element3 included in the subset.
Can anyone come up with a systematic way to generate all of the integers that would correspond to every subset of a given size? This is trivial for a subset of size 0, and for a subset of size n. It's pretty easy for a subset of size 1 and size n-1. But sizes 2, 3,..., n-2, n-3, ..., etc., are harder.
For size 1, I can do a loop,
integer = 1;
for(i = 0; i < n; i++)
{
integer = integer << 1;
}
this would give me 1, 2, 4, 8, 16, ..., 2^(n-1). Size n-1 can be found by inverting the bits of these integers.
For size 2, it's a bit harder, but one I've found that works is
for(i = 0; i < n; i++)
{
start = 1;
start = start + (1 << i);
integer = start;
while(integer < (1 << n))
{
integer = integer << 1;
}
}
This is not the only way I've found for size 2, but it's the cleanest.
Can someone please help me figure out a way to generate sets of size 3, 4, etc.?