This is a C++ program to generate all pairs of subsets, whose union make the Set.
Algorithms
Begin
function UnionSet():
Arguments:
a[] = an array.
n = number of elements.
Body of the function:
1) Generate binary code from 0 to 2^(n-1)-1 for all 2^(n-1) pairs.
2) Print the array element which has 0 or 1 in corresponding indexes in code string for each code.
3) Print them in a different set, which on the union of both sets gives the super set.
End
Example
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
void display(char code[], int a[], int n) //display the pairs
{
int i;
cout<<"\t{ ";
for(i = 0; i < n; i++) {
if(code[i] == '1')
cout<<a[i]<<" ";
}
cout<<"}";
cout<<" { ";
for(i = 0; i < n; i++) {
if(code[i] == '0')
cout<<a[i]<<" ";
}
cout<<"}\n";
}
void UnionSet(int a[], int n) {
int i, r, l;
char binary[n];
r = pow(2, n-1);
for(i = 0; i < n; i++)
binary[i] = '0';
for(i = 0; i < r; i++) {
display(binary, a, n);
l=n-1;
h:
if(binary[l] == '0')
binary[l] = '1';
else {
binary[l] = '0';
l--;
goto h;
}
}
}
int main() {
int i, n;
cout<<"\nEnter the number of elements: ";
cin>>n;
int a[n];
cout<<"\n";
for(i = 0; i < n; i++) {
cout<<"Enter "<<i+1<<" element: ";
cin>>a[i];
}
cout<<"\nThe possible subset pairs which on union generates the superset, are: \n";
UnionSet(a, n);
return 0;
}
Output
Enter the number of elements: 4
Enter 1 element: 4
Enter 2 element: 3
Enter 3 element: 2
Enter 4 element: 1
The possible subset pairs which on union generates the superset, are:
{ } { 4 3 2 1 }
{ 1 } { 4 3 2 }
{ 2 } { 4 3 1 }
{ 2 1 } { 4 3 }
{ 3 } { 4 2 1 }
{ 3 1 } { 4 2 }
{ 3 2 } { 4 1 }
{ 3 2 1 } { 4 }