Reputation: 11
I've been trying to get this done but i'm stuck right now. Can anyone please recommend the easiest way to get it done? Thank you
c[i] = a[i] + b[i];
// The snippet of code I have above works fine with operator: + - / *
// a[i] = { 1, 8, 13, 15 }
// b[i] = { 3, 8, 13, 20 }
// then c[i] = { 4, 16, 26, 35 }
// But how do i find the union and intersection of both arrays?
// I want the results to look like:
// union = {1,3,8,13,15,20}
// intersection = {8,13}
Upvotes: 1
Views: 66
Reputation: 119
since you asked for easiest way. you can put the elements of the arrays into 2 std::set
std::set<T> set1(begin(array1), end(array1));
std::set<T> set2(begin(array2), end(array2));
Then use std::set_union and std::set_intersection in 2 new std::set. Please take a look at the way its done in these links set union and set intersection Thus STL takes care of most of the logic and containers.
Upvotes: 2
Reputation: 5444
Try this..
//Unioin of 2 array
#include<stdio.h>
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
printf(" %d ", arr1[i++]);
else if(arr2[j] < arr1[i])
printf(" %d ", arr2[j++]);
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}
int main()
{
int arr1[] = {1, 8, 13, 15};
int arr2[] = {3, 8, 13, 20};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
printUnion(arr1, arr2, m, n);
getchar();
return 0;
}
//Intersection of two array
#include<stdio.h>
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
printf(" %d ", arr2[j++]);
i++;
}
}
}
int main()
{
int arr1[] = {1, 8, 13, 15};
int arr2[] = {3, 8, 13, 20};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
printIntersection(arr1, arr2, m, n);
getchar();
return 0;
}
Upvotes: 0