/**
* Write a description of class MagicSquare here.
*
* @author (Esteban Montes)
* @version (a version number or a date)
*/
import java.util.Random;
public class MagicSquare
{
public static final int MAX_DIM = 10;//10x10
public static final int DEFAULT_DIM = 5;
private int[][] dim;
public MagicSquare()
{
this.setDim(new int[DEFAULT_DIM][DEFAULT_DIM]);
//int[][] dim = {{1,14,14,4},{11,7,6,9},{8,10,10,5},{13,2,3,15}};
//this.dim = dim;
}
public MagicSquare(int dimension)
{
this.setDim(new int[dimension][dimension]);
}
public int[][] getDim()
{
return dim;
}
private void setDim(int[][] dim)
{
if(dim.length <= MAX_DIM)
this.dim = dim;
}
/**
* Method fillSquare
* Fill the matrix with random numbers between 1 and dim^2
*/
public void fillSquare()
{
Random randomNumber = new Random();
for(int i=0; i<this.getDim().length; i++){
for(int j=0; j<this.getDim().length; j++){
dim[i][j] = randomNumber.nextInt((this.getDim().length*this.getDim().length));
}
}
}
public void placeNumber(int row, int column, int number)
{
dim[row][column] = number;
}
public boolean isMagicSquare()
{
if(this.rowSum() == this.colSum() && this.rowSum() == this.diagSumL() && this.rowSum() == this.diagSumR())
return true;
else
return false;
}
private int rowSum()
{
int[] sums = new int[this.getDim().length];
int sum = 0;
for(int i=0; i<this.getDim()[0].length; i++){
for(int j=0; j<this.getDim().length; j++){
sum+=this.getDim()[i][j];
}
sums[i] = sum;
sum = 0;
}
int aux = sums[0];
for(int i=1; i<sums.length; i++){
if(sums[i] == aux)
aux = sums[i];
else
aux = 0;
}
return aux;
}
private int colSum()
{
int[] sums = new int[this.getDim().length];
int sum = 0;
for(int i=0; i<this.getDim()[0].length; i++){
for(int j=0; j<this.getDim().length; j++){
sum+=this.getDim()[j][i];
}
sums[i] = sum;
sum = 0;
}
int aux = sums[0];
for(int i=1; i<sums.length; i++){
if(sums[i] == aux)
aux = sums[i];
else
aux = 0;
}
return aux;
}
private int diagSumL()
{
int sum = 0;
for(int i=0; i<this.getDim().length; i++){
sum+=this.getDim()[i][i];
}
return sum;
}
private int diagSumR()
{
int sum=0;
int aux=this.getDim().length-1;
for(int i=0; i<this.getDim().length; i++){
sum+=this.getDim()[i][aux-i];
}
return sum;
}
}
Una tarea no presencial que mandarón como ejercicio obligatorio de seminario en mi facultad.