Dan Dan - 6 months ago 19
Java Question

Checking if one array is the reverse of another array in java

Im trying to create a method that take 2 int array as the input parameter and returns true if the array are reverse and false otherwise. This is what I have so far but it is wrong.

public static void main(String[] args)
{
int b,a;
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,14};
boolean check = true;

for (a=0;a<data1.length;a++)
{
for (b=data2.length-1;b>=0;b=b-1)
{
if (data1[a] != data2[b])
check=false
}
}
System.out.println(check);
}


My example is suppose to print true but it doesn't.I am assuming the 2 arrays are of the same length. Can anyone help?

Answer

You don't need two loops - you only need to loop once, using the index "normally" in one array, and from the other end for the other array:

public static boolean checkReversed(int[] x, int[] y)
{
    // For production code, possibly add nullity checks here (see comments)
    if (x.length != y.length)
    {
        return false;
    }
    // Loop through x forwards and y backwards
    for (int i = 0; i < x.length; i++)
    {
        if (x[i] != y[y.length - 1 - i])
        {
            // As soon as we've found a "mistake" we can exit:
            // This is simpler (IMO) than keeping a "check" variable
            return false;
        }
    }
    return true;
}
Comments