ISE-ComProg-After-Midterm/Week8/Assignment8/src/partA/IsReverse.java

38 lines
2.0 KiB
Java

//This code is written by Siwat Sirichai
package partA;
import java.util.Arrays;
public class IsReverse {
public static boolean isReverse(int[] a, int[] b) {
if (a==null&&b==null)return true; //Special Case #1: if a and b is null, result: true, return right away to prevent NullPointer exception.
if((a==null&&b!=null)||(a!=null&&b==null))return false; //Special Case #2: if only one of a or b is null, result: false, return right away to prevent NullPointer exception.
if (a.length != b.length)return false; //Special Case #3: if the length of a and b is not equal, result: false, return right away to prevent ArrayIndexoutofBound exception.
for(int i = 0;i<a.length;i++)if(a[i]!=b[a.length-i-1])return false; //This is compare the first element of a with the last element of b, then second first of a and second last of b, so on...
return true;//If none of the condition are met (both a and b is not null), the two array are the reverse of each other
}
public static void main(String[] args) {
int[] a = { 1, 2, 2, 3, 4, 5 };
int[] b = { 5, 4, 3, 2, 2, 1 };
int[] c = { 1, 2, 0, 3, 4, 5 };
int[] d = { 1, 2, 2, 3, 4, 5, 0 };
int[] e = { 0, 5, 4, 3, 2, 2, 1 };
int[] f = null;
int[] g = null;
System.out.println("isReverse(a,b):" + isReverse(a, b) + ", expected to be true");
System.out.println("isReverse(b,c):" + isReverse(b, c) + ", expected to be false");
System.out.println("isReverse(a,c):" + isReverse(a, c) + ", expected to be false");
System.out.println("isReverse(d,e):" + isReverse(d, e) + ", expected to be true");
System.out.println("isReverse(e,d):" + isReverse(e, d) + ", expected to be true");
System.out.println("isReverse(d,b):" + isReverse(b, d) + ", expected to be false");
System.out.println("isReverse(f,g):" + isReverse(f, g) + ", expected to be true");
System.out.println("isReverse(f,a):" + isReverse(f, a) + ", expected to be false");
System.out.println("isReverse(a,f):" + isReverse(a, f) + ", expected to be false");
}
}