首页 > 解决方案 > 如何检查 C 中的数组重复项

问题描述

我的 C 程序的目的是获取两个数组(都由唯一的数字组成)并将它们合并成一个新数组,消除它们之间的任何相同数字。但是,当我尝试合并两者时,它会打印出两个组合在一起的数组,而不会消除任何重复。

我的程序通过首先添加“array_A”中的元素来创建“array_C”。之后,它使用计数器变量检查“array_B”和“array_C”之间是否存在重复项。对于for循环检查的“array_C”中的每个值,如果“array_B”的值不等于“array_C”中的值,则计数器减1。如果在“array_C”中的所有值都检查完后, counter <= 0,这意味着“array_C”中没有该值的重复项,应将其添加到“array_C”的末尾。我使用“位置”变量来跟踪这一点。

        //Creation of array_C

        int length_C = length_A + length_B;
        int array_C[length_C];

        //Copying array_A to array_C

        for (i = 0; i < length_A; i++) {
          array_C[i] = array_A[i];
        }

        //Checking array_C against array_B for duplicates

        counter = length_A;
        int position = length_A;
        for (i = 0; i < length_B; i++) {
          for (j = 0; j < length_C; j++) {
            if (array_B[i] != array_C[j]) {
              counter--;
            } else {
              counter++;
            }
          }

          //this is the position tracker to add new value in array_C
          if (counter <= 0) {
            array_C[position] = array_B[i];
            position++;
          }
        }

如果我输入这个:

Enter the length of array 1: 6
Enter the elements of the array: 1 2 3 4 5 6
Enter the length of array 2: 6
Enter the elements of the array: 3 4 5 6 7 8

我希望结果应该是这样的:

Here is the merged array:
1 2 3 4 5 6 7 8

但相反,它看起来像这样:

1 2 3 4 5 6 3 4 5 6 7 8

所以显然出了点问题,它不理解它应该只添加不重复的变量。

标签: carraysmergeduplicates

解决方案


你的逻辑有缺陷。这就是为什么你会得到意想不到的结果。请参阅代码中的以下修订:

for (i = 0; i < length_B; i++) {
      int skip = 0;
      for (j = 0; j < length_C; j++) {
        if (array_B[i] == array_C[j]) {
          skip=1;
          break;
        } 
      }

      if(skip == 1) continue;
      array_C[position++] = array_B[i];
    }

推荐阅读