[FIXED] Comparing elements of two arrays

Issue

My method accepts two arrays of integers and returns true if

  1. The arrays are the same length and
  2. each a.element is less than the b.element of the same index.

It works for all my test cases except when int[] a = {1, 2, 3} and int[] b = {4, 5, 1}. It returns true even though a[2] > b[2]. The digitDifference check isn’t working correctly but I can’t see the error.

public static boolean allLess(int[] a, int[] b) {
    int i = 0;
    boolean sameLength = (a.length == b.length);
    boolean digitDifference = (a[i] < b[i]);
    for (i = 0; i <= a.length - 1; i++) {}
    return (sameLength && digitDifference);
}

Solution

Your for loop does nothing, so you are only comparing the elements in the first index of the arrays.

Your code should look something like this :

public static boolean allLess(int[] a, int[] b) {
    boolean sameLength = (a.length == b.length);
    if (!sameLength)
        return false;
    boolean digitDifference = true;
    for (int i = 0; i <= a.length - 1 && digitDifference; i++) {
        digitDifference = (a[i] < b[i]);
    }
    return digitDifference;
}

Now the for loop compares each pair of elements having the same index, and terminates once it finds a pair that violates your requirement that (a[i] < b[i]).

Another equivalent implementation without the flags :

public static boolean allLess(int[] a, int[] b) {
    if (a.length != b.length)
        return false;
    for (int i = 0; i <= a.length - 1; i++) {
        if (a[i] >= b[i])
            return false;
    }
    return true;
}

Answered By – Eran

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published