Reputation: 127
I have two arrays.
So the second array is a subset of the first array But not a subset if the second array is {5.3} or, {9.1} (right to left order.)
My code is
#include <stdio.h>
void subset(int set11[], int set12[])
{
int length1;
int set1[] = {1, 5, 3, 9, 7, 0, 5};
length1 = sizeof(set1) / sizeof(int);
int length2;
int set2[] = {5, 9};
length2 = sizeof(set2) / sizeof(int);
int i = 0;
int j = 0;
int count = 0;
for (i = 0; i < length1; i++)
{
if (set1[i] == set2[j])
{
count = 1;
}
}
printf(" is \n");
if (count == 1)
{
printf("is subset");
}
else
{
printf("not subset");
}
}
int main()
{
int set11[] = {1, 5, 3, 9, 7};
int set12[] = {5, 9};
subset(set11, set12);
printf("");
return 0;
}
I get output in all cases only not subset.
Upvotes: 2
Views: 631
Reputation: 68
You can run a nested loop to get hold of all the matching elements in the subset array
for (i = 0; i < length1; i++)
{
for(k = 0; k < length2; k++)
{
if (set1[i] == set2[k])
{
count == 1;
}
}
}
Outer loop is for the for the First array Inner loop to check for the element at any position in the subset/second array
set1[] = {1, 5, 3, 9, 7, 0, 5}; set2[] = {5, 9};
If we run a nested loop we will get all the subsets regardless of their positions in the second array(set2)
it wont matter if the set2 is {5,9} or {9,5} in any case the counter variable will increase.
Upvotes: 0
Reputation: 709
Applied some changes in logic. refer comments.
#include <stdio.h>
#include <stdbool.h>
void subset(int set11[], int set12[])
{
int length1;
int set1[] = {1,3,5,7,9};
length1 = sizeof(set1) / sizeof(int);
int length2;
int set2[] = {3,5};
length2 = sizeof(set2) / sizeof(int);
int i = 0;
bool isSubset = true; //will indicate weather the second array is subset or not
// int j = 0; //
int startPosition = 0; // will decide the starting position for searching in the main array. {set 2}
// int count = 0; //not needed; we will represent it with bool variable 'isSubset'.
for (i = 0; i < length2; i++) //Iterating through the subset array
{
bool isFound = false;
for (int j=startPosition;j<length1;j++){ //Iterating through the original array {set 1}
if (set2[i]==set1[j]){ //if element from second array is found in first array then...
isFound = true; //found the element
startPosition = j+1; //increasing the starting position for next search in the first array.
printf("\t%d found at %d\n",set2[i],j);
break;
}
}
if(isFound==false){ //if not found then this is not subarray.
printf("\t%d not found\n",set2[i]);
isSubset = false;
break;
}
}
// printf(" is \n");
if (isSubset)
{
printf("subset");
}
else
{
printf("not subset");
}
}
int main()
{
int set11[] = {1, 5, 3, 9, 7};
int set12[] = {5, 9};
subset(set11, set12);
printf("");
return 0;
}
Upvotes: 1