How to count the same number of elements between two arrays, excluding duplicates

So, I have A = {1,3,3,4}
B = {5,4,7,3}

I want to see how many times the elements of array B appear in array A, however I only want to count each element once in array A. Therefore, if 3 appears several times, 3 will be counted only once, and therefore forward.

Here my answer will be 2, since I have 3.4 that are in array B, which are also in array A.

This is what I have so far:

int count = 0; 
for(int z = 0; z <4; z++)
    {
      for(int y = 0; y <4; y++)
      {
         if(arrayA[z] == arrayB[y])
         {
            count++; 
         }
      }//end for loop 
    }//end for loop 

When I run this, I get 3. I know why. I count duplicates in an array A {3,3,4}. How not to count them? I am stuck.

This is a secondary feature that I’m stuck with all the time.

+4
4

( #, int 0).

        int[] totals = new int[10];
        int[] arrayA = new int[] { 1,3,3,4};
        int[] arrayB = new int[] { 5,4,7,3};
        for (int z = 0; z < 4; z++)
        {
            for (int y = 0; y < 4; y++)
            {
                if (arrayA[z] == arrayB[y])
                {
                    totals[arrayA[z]]++;
                }
            }//end for loop 
        }//end for loop

        // Count your numbers through indices 
        for (int i = 0; i < totals.Length; i++)
        {
          if (totals[i] > 0)
          {
            count++;
          }
        } //end for loop
+2

: 1. , . 2. . , .

Swift:

let A = [1,2,3,3,4,7]
let B = [3,4,1,2,5,7,8,3,2]
var C : [Int] = []

for (_,a) in A.enumerate() {
    if B.contains( a ) && !C.contains(a){
        C.append(a)
    }
}

, !

+1

, ( PHP) : :

$A = [1,2,3,4];
$B = [2,4,6,7];
$count = 0;
$b_count = array_count_values($B);
foreach($A as $val)
{
   if(in_array($val, $B) && $b_count[$val] == 1)
   {
      $count++;
   }
}
echo "Total number of elements =>  ".$count;
+1

, , , ,

// complexity O( n * log(n) ), which is fast enough.
// language c++
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    int i, j, count = 0;
    int A[] = {1,3,3,4}, B[] = {5,4,7,3};
    int lenA = 4, lenB = 4;

    // sorting, to overlook the repeated numbers.
    sort(A, A + lenA);
    sort(B, B + lenB);

    for(i=0, j=0; i<lenA; i++)
    {
        // ignoring the repeated A elements.
        if(i>0 && A[i] == A[i-1])
            continue;

        //we can ignore all the elements of B where it less than current A element.
        //this can be assured because of sorting.
        while(j<lenB && B[j]<A[i])
            j++;

        if(A[i] == B[j])
        {
            count++;
            j++;
        }
    }

    printf("%d\n", count);

    return 0;
}
+1

Source: https://habr.com/ru/post/1615159/


All Articles