0
for(int i = 0; i < aLenght; i++) {
    for(int j = 0; j < bLenght; j++) {
        if(aChars[i] == bChars[j]) {
            System.out.println(j +" == "+ i);
        }
    }
}

For instance the code above generates the following output:
3 == 0
5 == 0
4 == 1
6 == 1

Now I would like to check whether there exist successive numbers on both sides. For instance the example above would return true, because 3 == 0 and 4 == 1 are successive.

Lorenz Wöhr
  • 855
  • 3
  • 14
  • 22
  • Could you, please show us what data you used for your example. Also, `5 == 0` **and** `6 == 1` should return true (following your logic)? – zlakad Nov 08 '18 at 20:15
  • Possible duplicate: https://stackoverflow.com/questions/28419113/finding-consecutive-numbers-in-java – Fran Marzoa Nov 08 '18 at 20:42
  • Possible duplicate of [Finding Consecutive Numbers in Java](https://stackoverflow.com/questions/28419113/finding-consecutive-numbers-in-java) – Fran Marzoa Nov 08 '18 at 20:42

1 Answers1

2

try this

for(int i = 0; i < aLenght - 1; i++) {
    for(int j = 0; j < bLenght - 1; j++) {
        if(aChars[i] == bChars[j] && aChars[i + 1] == bChars[j + 1]) {
            return true;
        }
    }
}

notice that this covers the length of the array even when it iterates to ALenght - 1. Because when it reaches aLenght - 2, it will be compared with aLenght - 1 as well in (aChars[i] == bChars[j] && aChars[i + 1] == bChars[j + 1]). You can check it running this:

@Test
public void successive() {
    char[] a = new char[]{'a', 'b', 'x', 'z', 'y'};
    char[] b = new char[]{'r', 's', 't', 'a', 'b'};
    boolean isSuccessive = false;
    for (int i = 0; i < a.length - 1; i++) {
        for (int j = 0; j < b.length - 1; j++) {
            if (a[i] == b[j] && a[i + 1] == b[j + 1]) {
                isSuccessive = true;
            }
        }
    }
    assertTrue(isSuccessive);
}
elbraulio
  • 994
  • 6
  • 15
  • This only works partly good, because aLenght - 1 and bLenght - 1 doesn't cover the whole length of the arrays anymore. – Lorenz Wöhr Nov 08 '18 at 20:10
  • 1
    yes, because you can find the next successive numbers from 0 to lenght - 2. When you reach lenght -1 there is not a next number to check if it is successive. – elbraulio Nov 08 '18 at 20:14