Skip to content

Instantly share code, notes, and snippets.

@GrenderG
Last active August 29, 2015 14:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GrenderG/6556eb755f5c0731b9a9 to your computer and use it in GitHub Desktop.
comprobar matriz magica
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