与数组比较并返回缺少的项目?

时间:2015-03-11 21:53:03

标签: c

我不确定为什么我无法做到这一点,我花了一些时间在这上面,而且我没有得到我想要的东西。现在我很沮丧。我有一个列表LL []的所需项目,以及一个listLL []列表,其中可能包含来自LL []的项目,但是以任何随机顺序。我想把看不见的东西放在看不见的[]中,然后看不见。至少这是我的想法:(

unsigned int i=0, j=0, k=0;
unsigned int LL[] = {0xB173,0xB193,0xB14D,0xB14E};  //Desired items
unsigned int seenLL[5];  // Seen items
unsigned int unseen[5];  // For unseen items

printf("\n List of Logcodes seen in filtered view :");      
for(i=0;i<view->numFilters;i++){   // I can't explain this, as it's BIG
    if(flt->filterType == LOGCODE_TYPE ){ 
        printf(" 0x%04X,",flt->code);  // This will print the list of items in the view. Usually about 2 or 3 items
        seenLL[k]=flt->code;   // Copy them to seenLL[]
        k++;
     }
 } 
 k=0;
 // At this point though my seenLL[] has a few of my desired items, it also contains junk information, which I am unable to explain.

for(i=0;i<sizeof(LL)/sizeof(LL[0]);i++){
    for(j=0;j<sizeof(seenLL)/sizeof(seenLL[0]);j++){
        if(LL[i] != seenLL[j]){
            unseen[k]=LL[i];    // I was trying to copy to unseen[] items that are missing from the desired list LL[]
            k++;
        }
        //else{       // Dumb, but what if seenLL[] had items from LL[] but not in the same order as they are in the array LL[], it can occur in any order
         // if(sizeof(unseen)/sizeof(unseen[0])!=0)
        //      if(LL[i] == unseen[i]{ 
        //            k--;
        //            unseen[i]=0;
         //       }                     
    }
}
if(k>0) printf(" Missing Logs Pkts :");
if(k>0) for(i=0;i<sizeof(unseen)/sizeof(unseen[0]);i++)    //sigh! my pathetic attempt to print missing items.
     printf("%d,",unseen[i]);

3 个答案:

答案 0 :(得分:0)

您必须为seenLL的每个元素扫描LL数组,但要正确检测是否已看到该元素:

for (i = 0;i < sizeof(LL) / sizeof(LL[0]); i++) {
    for (j = 0; j < sizeof(seenLL) / sizeof(seenLL[0]); j++) {
        if (LL[i] == seenLL[j])
            break;
    }
    if (j >= sizeof(seenLL) / sizeof(seenLL[0])) {
        unseen[k++] = LL[i];    // scan went to the end, no match.
    }
}

我建议使用宏countof来澄清您的代码:

#define countof(a)  ((sizeof(a) / sizeof((a)[0]))

答案 1 :(得分:0)

逻辑错误。

您正在做什么:针对LL中的每个项目:如果它与seenLL中的某些项目不同,请将其添加到unseen。< / p>

您应该做什么:对于LL中的每个项目:如果它与seenLL中的每个项目不同,请将其添加到unseen

(考虑这两种可能逻辑的另一种方式:第一种检查某些项是否与seenLL中的每一项相同,而第二种检查它是否与某些项目相同seenLL。很明显,如果seenLL包含至少两个不同的项目,则第一次检查无法成功。)

答案 2 :(得分:0)

数组seenLL只有五个元素的空间,但如果LL有五个以上的元素,则没有任何建议或确保您尝试在其中记录的代码数量为5或更少

此外,在完成填充seenLL之后,您将丢弃变量k的值,它会告诉您seenLL中有多少元素实际包含有效数据。

稍后,您将LL的每个元素与seenLL的潜在所有元素进行测试,可能包括一些不包含有效数据的元素。实际上,您应该测试所有有效元素但不应该是无效元素,否则您可能会将所有元素都看作是看不见的(它们将无法匹配seenLL中的至少一个元素。)

数组unseen也只有五个元素的空间,但没有任何建议或确保您尝试在其中记录的代码数量为5或更少。

然后,最后,如果您确实识别出任何看不见的元素,则打印 unseen的每个元素,可能包括一些不包含有效数据的元素。

相关问题