Find all distinct subsets of a given set in C++

C++Server Side ProgrammingProgramming

Here we will see how to display all distinct subsets of a given set. So if the set is {1, 2, 3}, then the subsets will be {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}. The set of all subsets is called power set. The power set has 2n elements.

We will loop through 0 to 2n (excluding), in each iteration we will check whether the ith bit in the current counter is set, then print ith element.

Example

#include<iostream>
#include<cmath>
using namespace std;
void showPowerSet(char *set, int set_length) {
   unsigned int size = pow(2, set_length);
   for(int counter = 0; counter < size; counter++) {
      cout << "{";
      for(int j = 0; j < size; j++) {
         if(counter & (1<<j))
            cout << set[j] << " ";
         }
         cout << "}" << endl;
      }
   }
   int main() {
   char set[] = {'a','b','c'};
   showPowerSet(set, 3);
}

Output

{}
{a }
{b }
{a b }
{c }
{a c }
{b c }
{a b c }
raja
Published on 01-Nov-2019 10:47:40
Advertisements