# Compare both sides of a matrix in java

2

I'm trying to make a program that says if the matrix is the same from any side that looks at layers, that is, in the matrix

``````1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
``````

has a first layer of ones, then another of two and a last of three. To do this I take the lower and upper triangular, the latter inverted and compare and exit 112123122211111 twice, so they are equal. I have tried comparing both matrices or putting the numbers of the matrix in an array and then comparing it but it does not compare it to me, since in that matrix it would have to leave that it is the same. The code I have is:

``````public class matrizigual {

public static void main(String args[]) {

int[][] matriz = { { 1, 1, 1, 1, 1 }, { 1, 2, 2, 2, 1 },
{ 1, 2, 3, 2, 1 }, { 1, 2, 2, 2, 1 }, { 1, 1, 1, 1, 1 }, };
imprimirMatriz(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
int lado = matriz.length;
int[][] matriz1 = new int[lado][lado];
int[][] matriz2 = new int[lado][lado];

for (int i = 0; i < lado; i++) {
for (int j = 0; j <= i; j++) {
matriz1[i][j] = matriz[i][j];
System.out.print(matriz1[i][j]);

}

}
System.out.println();
System.out.println();

for (int i = lado - 1; i >= 0; i--) {
for (int j = matriz[i].length - 1; j >= i; j--) {

matriz2[i][j] = matriz[i][j];
System.out.print(matriz2[i][j]);

}
}
System.out.println();
if (matriz1 == matriz2) {
System.out.println("Es igual");

} else {
System.out.println("No es igual");
}

}
}
``````

asked by Fernando 24.01.2017 в 10:55
source

## 1 answer

2

You have to use the following comparator for matrices:

``````Arrays.deepEquals(matriz1, matriz2)
``````

The comparator `==` resolves that they are different objects (different references), you can try like this:

``````for (int i = 0; i < lado; i++) {
for (int j = 0; j <= i; j++) {
matriz1[i][j] = matriz[i][j];
matriz3[i][j] = matriz[i][j];

System.out.print(matriz1[i][j]);
}
System.out.println("");
}
``````

... and if you compare the matrices 1 and 3 with `==` , the result is false, however, with `Arrays.deepEquals(matriz1, matriz2)` the result is positive.

answered by 25.01.2017 в 17:36