I've been trying to make a simple function which checks if an array is the same as another array reversed.
For instance, comparing [0, 1, 2] and [2, 1, 0] would return true, but comparing [0, 1, 2] and [2, 1, 1] would return false.
I am also trying to use the divide and conquer method, using function recursively.
This is what I have coded, but it doesn't work as intended, returning false when it should return true:
public class ReverseCheck {
// Check if an array is the reverse of another array
// Use divide and conquer
public static boolean isReverse(int[] a, int[] b) {
if (a.length != b.length) {
return false;
}
return isReverse(a, b, 0, a.length - 1);
}
private static boolean isReverse(int[] a, int[] b, int start, int end) {
if (start == end) {
return a[start] == b[end];
}
int mid = (start + end) / 2;
return isReverse(a, b, start, mid) && isReverse(a, b, mid + 1, end);
}
public static void main (String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
int[] b = {6, 5, 4, 3, 2, 1};
int[] c = {1, 2, 3, 4, 5, 6, 7};
int[] d = {6, 5, 5, 3, 2, 1};
System.out.println(isReverse(a, b)); // Should return true, returns false
System.out.println(isReverse(a, c)); // Should return false, returns false
System.out.println(isReverse(a, d)); // Should return false, returns false
}
}