'Intersections of given sets with repeat of elements

Logic to count intersections in a given set is correct for no repetitive pattern, but for this set, the output count is wrong.

int a[] = {1,1,1,2};
int b[] = {1,1,2,2,3};
int count = 0;
for(int i=0;i<a.length;i++) {
for(int j =0;j<b.length;j++){
if(a[i]==b[j]) {
count++;
}
}
}

Code output is 8 Expected output to be 3



Solution 1:[1]

Your code works fine. It just does not take the intersection of sets.

First of all: your arrays are arrays, not sets. By general definition a set is does not have any duplicates in it.

So depending on what you actually need, you either need to first remove duplicates to get actual sets, or write code that counts whatever it is that you want to count.

As written now, it is probably helpful to see what it does exactly: It loops over a, and inside each "element" of a loops over b and then matches:

a[0] == b[0] # true, adds to results
a[0] == b[1] # true, adds to results
a[0] == b[2] # false
a[0] == b[3] # false
a[0] == b[4] # false

a[1] == b[0] # true, adds to results
a[1] == b[1] # true, adds to results
a[1] == b[2] # false
a[1] == b[3] # false
a[1] == b[4] # false

...

if you look at the whole list you'll see you get exactly the 8 matches.

Again, if you expect something else, then you need to code that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chai