Reputation: 13
I've to find cardinality of set union and set intersection of two sets from a data file. I've created two arrays(setA[] and setB[]) to store my data. a and b are the number of elements in set A and set B respectively. setIntersection should hold the result of intersection between set A and B. But I'm stuck at how should I find the union and intersection.
int printIntersection(int setA[], int setB[], int setIntersection[], int a, int b, int k)
{
int i = 0;
int j = 0;
while(i < a && j < b)
{
if(setA[i] < setB[j])
{
i++;
}
else if(setA[i] > setB[j])
{
j++;
}
else if (setA[i] == setB[j])
{
setIntersection[k] = setA[i];
i++;
j++;
k++;
}
cout<<"Cardinality of intersection is "<<k<<endl;
}
This code is for intersection but I'm not getting anything. And I don't know where to start on union. can anyone help me out with the code thanks! P.S I'm only allowed to use arrays and simple code algorithm. Thanks in advance!
Upvotes: 0
Views: 5016
Reputation: 7637
Use std::set_union and std::set_intersection, e.g.
int *c = std::set_union(setA, setA + a, setB, setB + b, setC)
int *c = std::set_intersection(setA, setA + a, setB, setB + b, setC)
where setC
is an output array of enough size; c
points to one past the last element of the constructed range.
If you want cardinalities, c - setC
is your answer.
I would recommend using something like std::vector
for representation, and iterators instead of arrays/pointers/lengths in algorithm calls.
Input ranges are assumed sorted; so is the output.
If you want to do it yourself, you'll find "possible implementations" at the links above.
Upvotes: 2