我有两个数组
- 1, 3, 5, 7, 9
- {3,5}或{1.9}。(从左到右顺序)
所以第二个数组是第一个数组的子集但如果第二个数组是{5.3}或{9.1},则不是子集(从右到左顺序)
我的代码是#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;
}
我得到所有情况下的输出,而不是子集
在逻辑上应用了一些变化。请参考评论。
#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 %dn",set2[i],j);
break;
}
}
if(isFound==false){ //if not found then this is not subarray.
printf("t%d not foundn",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;
}
您可以运行嵌套循环来获取子集数组中所有匹配的元素
for (i = 0; i < length1; i++)
{
for(k = 0; k < length2; k++)
{
if (set1[i] == set2[k])
{
count == 1;
}
}
}
外层循环用于for First数组检查子集/第二个数组
中任意位置的元素的内循环set1[] = {1,5,3,9,7,0,5};Set2 [] = {5,9};
如果我们运行一个嵌套循环,我们将得到所有的子集,而不管它们在第二个数组(set2)中的位置
无论set2是{5,9}还是{9,5},计数器变量都会增加。