Lorenz Wöhr
Lorenz Wöhr

Reputation: 871

Check if numbers are successive

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.

Upvotes: 0

Views: 137

Answers (1)

elbraulio
elbraulio

Reputation: 994

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);
}

Upvotes: 2

Related Questions