I need to write code that checks if the matrix is first Folded or not. Here's an example:
This is the code I wrote until now but I have an error.
public class test {
public static void main(String[] args) {
int[][] mat = { { 9, 2, 4 }, { 2, 9, 7 }, { 4, 7, 9 } };
boolean flag = true;
int stop = 0;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
System.out.print("[" + mat[i][j] + "]");
}
System.out.println();
}
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
if (i == j) {
j++;
if (i == mat.length - 1 && j == mat.length - 1) {
break;
}
}
if (i != j && mat[i][j] == mat[j][i]) {
flag = true;
} else {
flag = false;
if (flag == false) {
stop = 1;
i = mat.length - 1;
}
}
}
}
if (stop == 1) {
System.out.println("Not first folded matrix");
} else {
System.out.println("First folded matrix");
}
}
}
the error is:
[9][2][4]
[2][9][7]
[4][7][9]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at test.main(test.java:34)
How do we solve the problem? Is the code all right or not doing the test correctly?
thank you