tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 C Language > Advanced > Power Set

Power Set 

This example shows generating power set for the user given set. A powset is the one which contains all possible subsets of given set.

File Name  :  
source/C/advanced/power_set.c 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
01#include<stdio.h>
02#include<conio.h>
03 
04void print_set(int size, int *array, int n) {
05      
06     //printf("\nfor num : %d", n);
07      
08     int i, ele_count = 0;
09     printf("{");
10      
11     for(i=0; i < size; i++) {
12         if (n %2 == 1) {
13                
14             if (ele_count != 0) {
15                 printf(", ");
16             
17             printf("%d", array[i]); 
18             ele_count ++;
19         }
20          
21         n = n/2;
22     }
23      
24     printf("}");    
25}
26 
27 
28void print_powerset(int size, int *array) {
29 
30     int max = pow(2, size);
31     int i;
32      
33     printf("{ ");
34     for(i=0; i < max; i++) {
35          
36         if (i > 0) {
37             printf(", ");
38         }
39         print_set(size, array, i);
40     }
41     printf(" }");
42}
43 
44 
45int main(int argc, char *argv[]) {
46   int i, n, *array;   
47   printf("Enter the size of the integer set: ");
48   scanf("%d", &n);
49    
50   array=(int *)malloc(sizeof(int));
51 
52    printf("\nEnter the elements of the set : ");
53    for(i=0;i<n;i++)
54    {
55     scanf("%d", &array[i]);
56    }
57    
58   print_powerset(n, array);
59   getch();
60}

It gives the following output,
Enter the size of the integer set: 6

Enter the elements of the set : 1 2 3 4 5 6
{ {}, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}, {4}, {1, 4}, {2, 4}, {1,
 2, 4}, {3, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}, {5}, {1, 5}, {2, 5}, {1, 2,
5}, {3, 5}, {1, 3, 5}, {2, 3, 5}, {1, 2, 3, 5}, {4, 5}, {1, 4, 5}, {2, 4, 5}, {1
, 2, 4, 5}, {3, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}, {1, 2, 3, 4, 5}, {6}, {1, 6},
 {2, 6}, {1, 2, 6}, {3, 6}, {1, 3, 6}, {2, 3, 6}, {1, 2, 3, 6}, {4, 6}, {1, 4, 6
}, {2, 4, 6}, {1, 2, 4, 6}, {3, 4, 6}, {1, 3, 4, 6}, {2, 3, 4, 6}, {1, 2, 3, 4,
6}, {5, 6}, {1, 5, 6}, {2, 5, 6}, {1, 2, 5, 6}, {3, 5, 6}, {1, 3, 5, 6}, {2, 3,
5, 6}, {1, 2, 3, 5, 6}, {4, 5, 6}, {1, 4, 5, 6}, {2, 4, 5, 6}, {1, 2, 4, 5, 6},
{3, 4, 5, 6}, {1, 3, 4, 5, 6}, {2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6} }



 
  


  
bl  br