Set Theory (A-B)

Hi Guys! Help me with the code for relative complement. Here is what i've done so far.

char A[50];
char B[50];
int e;
int i;
int j;


cout<<"Enter number of Elements to input: ";
cin>>e;
cout<<endl;

for(i=0;i<e;i++)
{
cout<<"Enter element "<<i+1<<" of your Set A: ";
cin>>A[i];
}
cout<<"Set A = { ";
for(i=0;i<e;i++)
{
cout<<A[i];
if(i<e-1)
{
cout<<" , ";
}
}
cout<<" }";
cout<<"\n\n";


for(i=0;i<e;i++)
{
cout<<"Enter element "<<i+1<<" of your Set B: ";
cin>>B[i];
}
cout<<"Set B = { ";
for(i=0;i<e;i++)
{
cout<<B[i];
if(i<e-1)
{
cout<<" , ";
}
}
cout<<" }";
cout<<"\n\n";

It is my code for inputting the elements. Now, my problem is I can't crack the perfect code for Relative Compliment. I'm thinking of an if-else statement for this. Example if(A[0]==B[0]) like that. But I don't think it would bring me an output of A-B. Help!! Thanks :)
Last edited on
First, please use code tags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
char A[50];
 char B[50];
 int e;
 int i;
 int j;


 cout<<"Enter number of Elements to input: ";
 cin>>e;
 cout<<endl;

 for(i=0;i<e;i++)
 {
 cout<<"Enter element "<<i+1<<" of your Set A: ";
 cin>>A[i];
 }
 cout<<"Set A = { ";
 for(i=0;i<e;i++)
 {
 cout<<A[i];
 if(i<e-1)
 {
 cout<<" , ";
 }
 }
 cout<<" }";
 cout<<"\n\n";


 for(i=0;i<e;i++)
 {
 cout<<"Enter element "<<i+1<<" of your Set B: ";
 cin>>B[i];
 }
 cout<<"Set B = { ";
 for(i=0;i<e;i++)
 {
 cout<<B[i];
 if(i<e-1)
 {
 cout<<" , ";
 }
 }
 cout<<" }";
 cout<<"\n\n";


OK, so you have two arrays (sets) containing data, in order to find the relative compliment you need to find the values which exist in B but not in A...

I'll rephrase that, you need to search for the elements which exist in B but not in A.

So, search is a keyword here. You're look for a search algorithm. I'll give you a basic one that'd suit your problem, there are more advanced ways of doing this which will be faster.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

char C[50];
int k = 0;

for(int i = 0; i < 50; i++)
{
   bool unique = true;
    for (int j = 0; j < 50; j++)
    {
        if(A[j] == B[i])
        {
            /* It's not unique!*/
            unique = false;
            break;
        }            
    }

    /* We didn't find a match!*/
    if (unique)
    {
        C[k++] = B[i];
    }
}


This should find all of the unique members of B and store them in C with the count of C being k.

Last edited on
Topic archived. No new replies allowed.