In: Computer Science
Overlapping Arrays (C++)
An array overlaps another array if all elements of the latter array exist in the former array. They need not necessarily be in the same order. For example, [1,7,3,4,2] overlaps [1,2,3] because 1,2 and 3 exist in [1,7,3,4,2]. To make the implementation easy, [1,7,3,4,2] overlaps [1,1,2,3] as well. We don’t need to check whether 1 appears twice in the first array. Write a program that lets the user enter two arrays and displays whether the first array overlaps the second.
Program
#include <iostream>
using namespace std;
int isOverlap(int array1[], int array2[],int n1, int n2) ;
int main()
{
int n1,n2,i;
//Read the size of first and second array
cout<<"Enter size of first array: ";
cin>>n1;
cout<<"Enter size of second array: ";
cin>>n2;
int array1[n1],array2[n2];
//Read the elements of first and second array
cout<<"Enter first array: ";
for(i=0;i<n1;i++)
cin>>array1[i];
cout<<"Enter second array: ";
for(i=0;i<n2;i++)
cin>>array2[i];
//Call the function to check if first array overlaps second
array
if(isOverlap(array1,array2,n1,n2))
cout<<"First array overlaps the second
array."<<endl;
else
cout<<"First array does not overlaps the second
array."<<endl;
}
int isOverlap(int array1[], int array2[],int n1, int n2)
{
int i,j;
for (i = 0; i <n2; i++)
{
for (j = 0; j <n1; j++)
{
if(array2[i] == array1[j]) // Element found
break;
}
if (j == n1) //Second array not found in array1
return 0;
}
// All elements of array2 are present in array1
return 1;
}
Output
Enter size of first array: 5
Enter size of second array: 4
Enter first array: 1
7
3
4
2
Enter second array: 1
1
2
3
First array overlaps the second array.
Output
2
Enter size of first array: 4
Enter size of second array: 3
Enter first array: 1
6
7
3
Enter second array: 2
3
1
First array does not overlaps the second array.