Suppose you have two arrays: a1[0…n-1] of size n and a2[0….m-1] of size m. Write a program that checks whether a2[] is a subset of a1[] or not. Both the arrays may or may not be sorted. It can be assumed that elements within an array are distinct.
#include <iostream>
using namespace std;
//A function that checks if arr2 is a subset of arr1
bool is_subset(int a1[], int a2[], int m, int n)
{
int x = 0;
int y = 0;
for (x = 0; x < n; x++) {
for (y = 0; y< m; y++) {
if (a2[x] == a1[y])
break;
}
if (y == m)
return 0;
}
return 1;
}
// Testing code
int main()
{
int a1[] = {1,2,3,4,5,6,7,8,9 };
int a2[] = { 4,5,6 };
int size_a1 = sizeof(a1) / sizeof(a1[0]);
int size_a2 = sizeof(a2) / sizeof(a2[0]);
if (is_subset(a1, a2, size_a1, size_a2))
cout<<"a2 array is asubset of array a1 ";
else
cout<<"array a2 is not a subset of array a1";
return 0;
}
Comments
Leave a comment