-3

for Example:

int[] a = [0,1,2,3,4,5];
int[] b = [3,4,5,6,7,8];

count = 3;

The arrays do not have to be consecutive numbers. How would I get the number of values that equal between these arrays?

edit: So I've attempted the following:

List<int[]> w = Arrays.asList(winning);
List<int[]> s = Arrays.asList(F1Select);            
w.retainAll(s);
int equalNums = w.size();

But I'm getting the following error for the retainAll line:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
    at java.util.AbstractList$Itr.remove(Unknown Source)
    at java.util.AbstractCollection.retainAll(Unknown Source)
Gordon Li
  • 25
  • 2

3 Answers3

4

You can just convert to lists, and find the intersection using retainAll.

List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainAll(bList);
return aList.size();

aList will then only contain items that are also in bList, and the size of aList lets you know the count.

If you want only unique values you could convert the arrays to a Set and do the same thing.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
1

Try this :

 Integer[] a = new Integer[]{0, 1, 2, 3, 4, 5};
 Integer[] b = new Integer[]{3, 4, 5, 6, 7, 8};

  List<Integer> list1 = Arrays.asList(a);
  Set<Integer> commonSet = new TreeSet<Integer>();
     for (Integer i : b) {
         if (list1.contains(i)) {
           commonSet.add(i);
            }
        }

        System.out.println(commonSet.size());
Community
  • 1
  • 1
Alya'a Gamal
  • 5,624
  • 19
  • 34
0

If your are allowed to have O(m + n) additional space used during computation, you can keep a HashMap for each array. The key is each array element, the value is how many times it occurs. Once you've computed how often each number occurs, then you've simplified the problem to comparing the two maps.

Whenever you have a key present in both maps, you have a number that is present in both arrays. The values can let you decide how many times the number is present in both arrays.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52