GeeksforGeeks » Algorithms
Power Set and Permutation of a set
(5 posts)-
Write a program to print power set of a given set
-
#include<stdio.h> #include<math.h> void power_set(int *,int); void print_array(int *,int); int main() { int a[] = {1,2,3}; printf("\n==Input Array==\n"); print_array(a,3); power_set(a,3); return 0; } void power_set(int *a, int count) { int i,j; printf("NULL SET"); for(i=0;i<pow(2,count);i++) { for(j=0;j<count;j++) { if(i & (1<<j)) printf("%d",a[j]); } if(i == (pow(2,count) -1)) printf("\n"); else printf(", "); } } void print_array(int *a, int count) { int i; for(i=0;i<count;i++) printf("%d ",a[i]); printf("\n"); return; } -
Finding a power set is equivalent to finding combinations of a string.
Track array keeps track of the characters included in the power set.
void combination(int depth,char *arr,int start,char *comb,int* track) { int i; if(depth<SIZE) for(i=start;i<SIZE;i++) if(!track[i]) { track[i]=1; comb[depth]=arr[i]; comb[depth+1]=''; printf("%s\n",comb); combination(depth+1,arr,i,comb,track); track[i]=0; } }
Reply
You must log in to post.