All subsets of a given set problem
This is a simple C program to print all the subsets of a given set. There will be (2n) subsets for a given set with n elements.
for (long i = (1 << setsize) -1; i >0 ; --i)
set is the array of integers for which we need all subsets.
setsize is the number of elements in the set.
The for loop simply covers all the subsets, hence it executes (2n) times.
It uses a simple way to calculate subset. Assume the subset index i to be a binary number. Then it will print the element j from the set, if in i j is set. e.g. if i = 23.
i = 16 + 4 + 2 + 1 = 24 + 22 + 21+20.
Hence for i=23, the program will simply print 4th, 2nd, 1st and 0th indexed element from set.
Just give some time with the program and you will easily undestand how it works.
Currently I am trying to do the same thing using recursion and without using any extra space. The obvious solution is at any step adding current element to all the subsets created before that step. But this will surely take 2n space.
int main(void)
{
int set[] = {1,2,3,4,5,6,7,8};
const int setsize = sizeof(set) / sizeof (*set);
for (long i = (1 << setsize) -1; i >0 ; --i)
{
int index = setsize - 1;
int n = i;
cout<<'{';
while (n > 0)
{
if (n % 2)
{
printf(" %d ", set[index]);
}
--index;
n /= 2;
}
cout<<'}'<<" ";
}
return 0;
}
set is the array of integers for which we need all subsets.
setsize is the number of elements in the set.
The for loop simply covers all the subsets, hence it executes (2n) times.
It uses a simple way to calculate subset. Assume the subset index i to be a binary number. Then it will print the element j from the set, if in i j is set. e.g. if i = 23.
i = 16 + 4 + 2 + 1 = 24 + 22 + 21+20.
Hence for i=23, the program will simply print 4th, 2nd, 1st and 0th indexed element from set.
Just give some time with the program and you will easily undestand how it works.
Currently I am trying to do the same thing using recursion and without using any extra space. The obvious solution is at any step adding current element to all the subsets created before that step. But this will surely take 2n space.
0 Comments:
Post a Comment
<< Home