0

Hi, I'm a newbie to Java and I was doing this lab assignment where we compare elements of two arrays to get the common elements. I am stuck on how to get rid of duplicates.

My current code is giving me the output [3, 0, 5, 6, 5, 0, 9, 0] and the desired output of common is [3, 5, 6, 9, 0, 0, 0, 0].

Also, since I am not that experienced, please do not post professional ways to do the problem or "experienced" answers to my question, as that would not help me at all :D.

Thanks!

 public static void main (String[] args) {
    int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
    int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
    int[] common = new int[a1.length];
    System.out.println("Exercise 3: ");
    findCommon(a1,a2,common);
 }



public static void findCommon(int[] a1, int[]a2, int[] common) {
    int num = 0;

      for (int i = 0; i < common.length; i++)
      {
          for (int j = 0; j < a2.length; j++)
          {
              if (a1[i] == a2[j]) // loops through every index of j, while keeping i at one index
                  num = a1[i];
                  for (int k = 0; k < common.length; k++) // makes sure there are no duplicates in common
                 {
                     if (num != common[k]) 
                      common[i] = num;
                 }
          }
      }

      for (int elements : common)
          System.out.print(elements + " ");
  }
  • 2
    Possible duplicate of [Java - Finding unique elements in two different arrays](https://stackoverflow.com/questions/44493858/java-finding-unique-elements-in-two-different-arrays) – Logan May 28 '18 at 21:54
  • Well not exactly a duplicate, though the intersection is derived in the top solution as an intermediate result. I like [this](https://stackoverflow.com/questions/50573737/comparing-two-arrays-and-then-making-another-array-with-common-elements-and-no/50573975#50573975) answer because it solves the problem in terms of arrays. – DavidW May 28 '18 at 22:37

2 Answers2

1

You should look into using Sets to do this kind of thing, but since this is an exercise I've provided a solution with some comments along the way in the code.

Basically you should break the problem down into pieces, each of which is its own method. That way you will have an easier time getting it straight.

  1. arrayIntersect(int[], int[])

    This method's job is to create an array from two arrays. The resulting array must have unique elements that are present in both arrays.

You can do n. 1 with a helper method (mentioned below).

  1. inArray(int, int[])

    This method returns true if an array contains the given element, false otherwise.

Example

public static void main (String[] args) {
    int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
    int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};

    int[] a3 = arrayIntersect(a1, a2);

    for (int a : a3) {
        System.out.println(a);
    }
}

private static int[] arrayIntersect(int[] a1, int[] a2) {
    int[] intersect = new int[Math.min(a1.length, a2.length)];

    int curIndex = 0;
    for (int x : a1) {
        if (inArray(x, a2) && !inArray(x, intersect)) {
            intersect[curIndex] = x;
            curIndex++;
        }
    }

    // resize intersect array to not include unused indexes
    int[] tmp = intersect;
    intersect = new int[curIndex];

    for (int i = 0; i < intersect.length; i++) {
        intersect[i] = tmp[i];
    }

    return intersect;
}

private static boolean inArray(int element, int[] array) {
    boolean result = false;

    for (int a : array) {
        if (element == a) {
            result = true;
            break;
        }
    }

    return result;
}
geco17
  • 5,152
  • 3
  • 21
  • 38
  • 1
    Marked you up for providing a correct solution, but outside of an exercise I would generally prefer to see `System.arraycopy()` used instead of manually copying an array. – DavidW May 28 '18 at 22:32
0

You are very close to the correct anwser, but the for loop for (int k = 0; k < common.length; k++) is being executed for every element of a2. So, when an value exist for a1 but doesn't exist for a2, you are putting the old value of num at the common array. If you look at the elements printed, you will see that every time that an element just exist in a1, the element repeat. The result of the code is

3 3 5 6 5 5 9 9

You put the right identation, but forgot the curly brackets. If you put the curly brackets at the if (a1[i] == a2[j]), this will be the result:

3 0 5 6 5 0 9 0

But why these 0 are there? Because when you create an int array in java, all elements start with the value of 0. And you are putting the common elements at the same position of the presence of this elements in the a1 array. You can correct this by populating the int array with an invalid number and them ignorin it. At this code, I assumed that -1 is an invalid value.

public static void findCommon(int[] a1, int[] a2, int[] common) {
    int num = 0;
    for (int i = 0; i < common.length; i++) {
        common[i] = -1;
    }

    for (int i = 0; i < common.length; i++) {
        for (int j = 0; j < a2.length; j++) {
            if (a1[i] == a2[j]) { // loops through every index of j, while keeping i at one index
                num = a1[i];
                for (int k = 0; k < common.length; k++) // makes sure there are
                // no duplicates in common
                {
                    if (num != common[k])
                        common[i] = num;
                }
            }
        }
    }

    for (int elements : common) {
        if (elements != -1)
            System.out.print(elements + " ");
    }
}

If you see, At the if (elements != -1) I didn't put the curly brackets but it worked. If you don't put the curly brackets, it will just execute the next command.

LucasDelboni
  • 119
  • 1
  • 4
  • I get what you are doing, and thank you for not complicating the code too much. However, (I forgot to mention this), the desired output for my code is 3 5 6 9 0 0 0 0, which should print the whole common array, but just print zeros for the indices that have not been changed. Do you know how to modify the code to do this? –  May 28 '18 at 23:28
  • You are always putting the common element at the position that it first appeared at the a1 array. You can create another int that saves in wich position you will put that element. So, always after put some value at the common array, you increase that int by one. At start, the aux value is 0, after you put the first element at position common[aux], you do an aux++. Since I cant comment in your question, I suggest you to put the result of your current code in the question. Normally, it helpes to find the anwser. – LucasDelboni May 29 '18 at 00:03
  • Thank you, I figured it out! I used an index variable (declared outside of the for loops) which I used to increment the common[]. I also used a boolean value, that would reset to false in the j-loop, and would be the sole statement in the k - loop. Before, the common[] was not getting fully checked I think, so I moved my if statement outside of the k-loop –  May 29 '18 at 03:41