I'm trying to compare first and second half of an array. For example: [3, 7, 7, 3]
, 3, 7
is the first half and 7, 3
is the second half. I tried with nested loops but it haven't worked so far. Here is my code and the question is what is wrong with it?
int [] arr = {3, 7, 7, 3};
boolean isMirror = false;
for (int i = arr.length/2 -1; i>=0; i--) {
for (int j = arr.length/2; j < arr.length; j++) {
if (arr[i] == arr[j]) {
isMirror = true;
break;
} else {
isMirror = false;
break;
}
}
}
if (isMirror) {
System.out.println("The array is mirror-like");
} else {
System.out.println("The array is not mirror-like");
}
Issue is you are comparing 7
with 7
and 3
using nested loop hence, isMirror
will be false
so remove nested loop and use two variable with single loop
boolean isMirror=true;
for(int i=0, j = arr.length-1; i<arr.length/2;i++,j--){
if(arr[i]!=arr[j]){
isMirror=false;
break;// not equal so go out
}
}
If you want to find a mirror, just one loop needed:
set boolean mirror = true;
walk from i=0 (first element) to the mid of the array length (say n/2).
if array[i] != array[maxlength - i]
set mirror = false, and the you may end
You just need one loop and set isMirror = false
when arr[i]
and arr[j]
don't equal:
int[] arr = {3, 7, 7, 3};
boolean isMirror = true;
for (int i = 0; i <= arr.length/2; i++) {
int j = arr.length - 1 - i;
if (arr[i] != arr[j]) {
isMirror = false;
break;
}
}
if (isMirror) {
System.out.println("The array is mirror-like");
} else {
System.out.println("The array is not mirror-like");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.