Sunday 30 October 2011

Magic Square

My next post is about Magic Square :-

What is Magic Square?

The magic square is matrix of n*n elements in which the addition of any row elements, column elements or diagonal elements will produce the same result.


There are many ways to generate the Magic Square, and the logic i used is explained below :-

There are 3 arrays.

1st array contains the number written in array, for example if we have to generate the 3*3 square , then array 1 contain these elements :-

1     2     3
4     5     6
7     8     9

Array 2nd is written in such a fashion that the middle column occupy the elements in order and its adjacent rows are incremented/decremented order.

3     1     2
1     2     3
2     3     1

Array 3rd is exactly the image of array 2nd, so the array 3rd is

2     1     3
3     2     1
1     3     2

Now with the help of these 3 arrays, we are able to create our magic square.

Magic Square [row][column] = Array 1 [array 2 [row][column]][array 2 [row][column]

 Magic Square [1][1] = Array1[3][2]

because, array2 [1][1] = 3, and array3 [1][1] = 2

So, in this manner we are able to calculate all the results. :)

Thats it. The code will be in my next post.

Thanks.

No comments:

Post a Comment