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
CodePudding user response:
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.
CodePudding user response:
Try the following code. I use Math.min() for the second statement of for-loop to avoid IndexOutOfBounds error
public static void main(String[] args) {
int a[] = {1,1,1,2};
int b[] = {1,1,2,2,3};
int count = 0;
int min_len = Math.min(a.length, b.length);
for(int i=0;i< min_len;i ) {
if(a[i]==b[i]) {
count ;
}
}
System.out.println(count);
}
Output is 3