0

Lets say I have a class called "Sequence". This class has an instance variable private int[] tab. There are also some methods to create this tab like those:

public Sequence() {
    this.tab = fillAnArray(drawsNumber(5, 20));
}

private int drawsNumber(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Wrong range");
    }
    return new Random().nextInt(max - min + 1) + min;
}

public int[] fillAnArray(int size) {
    int[] arr = new int[size];
    arr[0] = 1;
    for (int i = 1; i < arr.length; i++) {
        arr[i] = drawsNumber(arr[i - 1], arr[i - 1] + 10);
    }
    return arr;
}

Now, I would like to create the method that accepts two Sequence objects as arguments and returns number of the same tab elements. So, I created method like this:

public int howManyCommonElements(Sequence c1, Sequence c2) {
    int i = 0, j = 0;
    int counter = 0;
    while (i < c1.tab.length && j < c2.tab.length) {
        if (c1.tab[i] == c2.tab[j]) {
            ++counter;
        } else if (c1.tab[i] < c2.tab[j]) {
            ++i;
        } else {
            ++j;
        }
    }
    return counter;
}

How do I compare single elements like c1.tab[i], c2.tab[j]?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
viverte
  • 43
  • 7
  • 1
    What do you mean you don't know how to compare? What is wrong with `c1.tab[i] == c2.tab[j]`? BTW it is bug in your code, if tabs have common element your loop will never finish. – talex Sep 28 '20 at 07:40
  • Ouch, i just tried to use something different than for loop. Youre right, i do not know how i could not see the problem. – viverte Sep 28 '20 at 07:50
  • Does this answer your question? [finding common elements in two integer arrays java](https://stackoverflow.com/questions/40632887/finding-common-elements-in-two-integer-arrays-java) – Abra Sep 28 '20 at 07:52
  • is it possible to use Lists instead of int arrays? – Dropout Sep 28 '20 at 08:04

2 Answers2

0

You have to compare every element of the 1st array with every element of the 2nd one. To do that you have to use 2 nested for cycles:

for (int i = 0; i < c1.tab.length; i++)
    for (int j = 0; j < c2.tab.length; j++)
        if (c1.tab[i] == c2.tab[j])
            ++counter;
LucaBonadia
  • 91
  • 2
  • 12
  • 1
    No, elements are ordered, you don't need to make it `O(n*m)` out of existing `O(n+m)`. – talex Sep 28 '20 at 07:50
0

If you have ordered elements (ASC), you can do like;

    int i = 0, j = 0;
    int counter = 0;
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] == arr2[j]) {
            ++i;
            ++j;
            ++counter;
        } else if (arr1[i] < arr2[j]) {
            ++i;
        } else {
            ++j;
        }
    }
SSC
  • 2,956
  • 3
  • 27
  • 43
  • Dude, the elements are already ordered asc... Idk if you noticed but the OP resolved the issue from the comments, even before the answers added here. – dbl Sep 29 '20 at 08:11