I want to implement a function in C++ that returns the set difference between 2
ID: 3789669 • Letter: I
Question
I want to implement a function in C++ that returns the set difference between 2 arrays ,
the set difference is the set of objects in set A - the objects in A intersection B
for example :
if we have set1 = {1,3,5} and set2 = {3,4,5} then the set difference is 1
so i have implemented the setIntersection function properly , but my setDifference function does not work properly here is the code:
// need imporvement on this one ???
int setDifference(int list1[], int list2[], int m, int n) //difference function
{
int i = 0, j = 0;
int *C ;
while(i < m && j < n)
{
if(list1[i]!=list2[i])
{
C[i]= list1[i];
}
}
for(int k=0;k<i;k++) //printing value after (A-B) difference
{
cout<< C[k]<<endl;
}
return *C;
}
// this one works just fine for an ordered array
int setIntersection (int list1[], int list2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if (list1[i] < list2[j])
i++;
else if (list2[j] < list1[i])
j++;
else
{
cout << list2[j++]<<",";
i++;
}
}
}
// this is the driver method
int main()
{
int list1 [] = {1,2,3,4,5,6};
int list2 [] = {1,3,5};
int size1 = sizeof(list1) / sizeof(list1[0]);
int size2 = sizeof(list2) / sizeof(list2[0]);
// call the function here
cout << "Union set: " << endl;
setUnion(list1, list2, size1, size2);
cout<< " Intersection set: " << endl;
setIntersection(list1, list2, size1, size2);
cout<< " Difference set: " << endl;
setDifference(list1, list2, size1, size2);
return 0;
setDiff(list1, list2, size1, size2);
}
Explanation / Answer
change your setDiff method with this new setDifference method -----
int *setDifference(int *list1, int *list2, int size1, int size2)
{
int *intersection=NULL, *temp=NULL, n=0, i=0, j=0;
try{
temp=new int[size1];
}catch(bad_alloc xa){
cout<<" Dynamic memory allocation failed ";
exit(0);
}
while(i<size1 && j<size2)
{
if(list1[i]==list2[j])
{
i++,j++;
}
else if(list1[i]<list2[j])
{
temp[n++]=list1[i++];
}
else
{
j++;
}
}
while(i<size1)
{
temp[n++]=list1[i++];
}
try{
intersection=new int[n];
}catch(bad_alloc xa){
cout<<" Dynamic memory allocation failed ";
exit(1);
}
for(j=0;j<n;j++)
{
intersection[j]=temp[j];
}
delete [] temp,temp=NULL;
cout<<" Set Difference ";
for(j=0;j<n;j++)
cout<<intersection[j]<<endl;
return intersection;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.