comprobar matriz magica
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static boolean check (int[][] m) { | |
int masterSum = 0; | |
int tempSumRow = 0; | |
int tempSumCol = 0; | |
int diagonal = 0; | |
for (int i = 0; i < m.length; i++){ | |
for (int j = 0; j < m[0].length; j++){ | |
// Almacenamos el valor de cada columna y fila temporalmente | |
tempSumRow += m[i][j]; | |
tempSumCol += m[j][i]; | |
// Si nos encontramos en la primera pasada, aprovechamos para obtener la diagonal | |
if (i == 0) | |
diagonal += m[j][j]; | |
} | |
// Si las columnas suman distinto | |
if (tempSumRow != tempSumCol) | |
return false; | |
else if (tempSumRow != diagonal) | |
return false; | |
/* Guardamos el valor maestro para compararlo solo una vez, a partir de ese momento simplemente | |
comparamos el valor maestro con el temporal */ | |
if (i == 0) | |
masterSum = tempSumRow; | |
else if (tempSumRow != masterSum) | |
return false; | |
tempSumRow = 0; | |
tempSumCol = 0; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment