Friday, 20 May 2016

Two Dimensional Array - The Magic Square


A Magic Square is a grid of unique numbers such that each row, each column and each diagonal add up to the same number.

Examples:
import java.util.Scanner;
class MagicSquare
{
  private int[][] magic;
  private int size;
  MagicSquare(int size)
  {
 this.size=size;
 magic=new int[size][size];
 Scanner input=new Scanner(System.in);
 System.out.println("Input values for Magic Square:");
 for(int i=0;i<size;i++)
 {
  for(int j=0;j<size;j++)
  {
   magic[i][j]=input.nextInt();
  }
 }
  }
  public boolean isMagic()
  {
boolean check=true;
int sum=0;
    int sumD1=0;
    int sumD2=0;
    for(int i=0,j=size-1;i<size;i++,j--)
{
sumD1+=magic[i][i];
sumD2+=magic[i][j];
if(sumD1==sumD1)
sum=sumD1;
else
return false;
}
for(int i=0;i<size;i++)
{
int sumOfRows=0;
int sumOfColumns=0;
for(int j=0;j<size;j++)
{
 sumOfRows+=magic[i][j];
 sumOfColumns+=magic[j][i];
}
if(sum!=sumOfRows || sum!=sumOfColumns)
return false;
}
return check;
  }
  public String toString()
  {
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
 System.out.print(magic[i][j]+" ");
}
System.out.println("");
}
return "";
  }
}
class MagicSquareTest
{
  public static void main (String [] args)
  {
Scanner input=new Scanner(System.in);

System.out.println("Magic square size?:");
int size=input.nextInt();

  MagicSquare ms = new MagicSquare(size);

  if (ms.isMagic())
  System.out.println (ms + "\nis a Magic Square");
  else
  System.out.println (ms + "\nis not a Magic Square");
  System.out.println ();
  }
}

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete

Hi,

Thanks for coming here. I hope this information helps you for preparing Java Interview.

Br,
Sachin Singh