Friday 12 August 2011

Magic Square

I designed an interesting program

I wrote code for the creation and initialization
of a magic square of the given odd size. I implemented the
following algoritm:

- put 1 in the middle cell of the first row;
- every next value must be placed in a cell
one row up and one column right relative to the previous one;
- if the destinaton of the next cell appears outside of the
array, enter the later from the opposite end;
- if the destinaton of the next cell is already occupied,
then move just one row down relative to the previous cell.

For example,

for size = 3,

8    1    6
3    5    7
4    9    2

the sum of all rows and columns is 15


Here is the code
class Grid
{
int num;
public void fillGrid(int n)
{
int ar[][]=new int[n][n];
num=n;
fill(ar);
int r=0,c=n/2,i;
for(i=1;i<=(n*n);i++)
{
if(ar[r][c]==0)
ar[r][c]=i;
else
ar[++r][c]=i;

/*printArray(ar);
System.out.println("\n\n\n\n");*/

if((r-1)<0 && (c+1)>=n)
r++;
else
{
if((r-1)<0)
{
r=n-1;
c++;
}
else if((c+1)>=n)
{
r--;
c=(c+1)-n;
}
else if(ar[r-1][c+1]==0)
{
r--;
c++;
}
}
}
printArray(ar);
}
void fill(int Ar[][])
{
int i,j;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
Ar[i][j]=0;
}
}
void printArray(int Ar[][])
{
int i,j;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
System.out.print("\t "+Ar[i][j]);
System.out.println("");
}
}
}


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete