0

For example, the following question states:

Write a method which takes two array of integers as parameter and prints all their common elements.

My attempt:

public static void commonElements(int[] A, int[] B)
{
    for(int i = 0; i < A.length; i++)
        for(int j = 0; j < B.length; j++)
            if(A[i] == B[j])
                System.out.print(A[i] + " ");
}

Now, the problem is that this code works only if the elements in each array occurs only once. But for example if in array A there were two 4s and in array B there were four 4s, the output would be eight 4s, which is wrong!

So, how can I check if a certain element in an array has already occured so that the code won't take it in account.

Kj45
  • 79
  • 2
  • 2
  • 11
  • if it is `found` then `break` – Scary Wombat Dec 16 '15 at 00:31
  • The code you need can be found in [Jacorb Effect's answer in this question on Stack Overflow](http://stackoverflow.com/questions/4529819/finding-common-elements-in-two-arrays-of-different-size). – Steven Dec 16 '15 at 00:33

2 Answers2

0
public static void commonElements(int[]A, int []B){

    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++;
                break;
            }       
    System.out.println(count);
}

Give this a try. By adding break you force it out of the loop.

DanZoe
  • 111
  • 1
  • 3
  • 15
0

You can store what you found in a set. A set doesn't allow for duplicates.

public static void commonElements(int[] a, int[] b)
{
    Set<Integer> duplicates = new LinkedHashSet<Integer> duplicates;
    for(int i = 0; i < a.length; i++){
        for(int j = 0; j < b.length; j++){
            if(a[i] == b[j]){
                duplicates.add(a[i]);
            }
        }
    }
    System.out.println(String.join(" ", duplicates));
}

Note: Variable names should be lowercase in Java, by convention.

Adam
  • 43,763
  • 16
  • 104
  • 144