Sunday, March 4, 2012

All subsets of a given set

If we're given a set of integers such that S = {1, 2, 3}, how can we find all the subsets of that set? For example, given S, the subsets are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, and {1, 2, 3}.

http://algorithms.tutorialhorizon.com/print-all-the-subsets-of-a-given-set-power-set/
http://www.geeksforgeeks.org/power-set/

Alternative Questions:
http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/
http://algorithms.tutorialhorizon.com/print-all-n-length-strings-from-given-number-k/
http://algorithms.tutorialhorizon.com/all-n-length-strings-from-given-string-of-length-k/
http://tech-queries.blogspot.in/2015/08/print-all-tuple-combinations-for-given.html

Strategy:
To solve this problem there are two techniques that we need to understand:
  1. Determine the number of subsets using bit strings: we know that the number of subsets equals to 2 to the power of the number of elements in the superset: #subsets = 2 ^ #elements. For instance, if our superset is S = {1, 2, 3}, then it has 2^3 = 8 subsets. If our superset has four elements then it has 2^4 = 16 subsets. Moreover, by shifting the bit representation of the number 1 by n, we also get 2^n. Thus, if we shift the bit string of 1 by the number of elements in the superset, we'll get the number of subsets for that superset. For example, if we have S = {1, 2, 3}, then there are 1 << 3 = 2^3 subsets in S.
  2. Keeping track of data using bit manipulation: for this problem, we will use a bit string to keep track of subsets and their elements. Take S = {1, 2, 3} as an example. If the bit string is 100 then the subset we're working on has only one element which is 1. If the bit string is 110 then the subset we're working on has two elements which are 1 and 2. We will use & and << bit operators to figure out which bit is 1 in the bit string.
 Code:
 #include<stdio.h>
#include<stdlib.h>
void findSubsets(int arr[],int len)
{
  int numOfSubsets = 1 << len;

  for(int i = 0; i < numOfSubsets; i++)
 {
    int pos = 0;
   int bitmask = i;

   printf("{");
   while(bitmask > 0)
   {
    if((bitmask & 1) == 1)
       printf("%d",arr[pos]);
    bitmask >>= 1;
    pos++;
   }
   printf("}\n");
 }
}

int main(){
    int arr[]={1,2,3};
    int len=sizeof(arr)/sizeof(arr[0]);
    findSubsets(arr,len);
    getchar();
    return 0;
}

No comments:

Post a Comment