A magic square is one where the total of rows, columns and diagonals is the same.
Take a 3x3 magic square.
The Rules are pretty simple. The rule is called top-left rule.
1. Start with 1. Put it in the centre of the 1st row. So 1 is in (1,2) Row 1, Col 2.
2. Goto top left. In this case top is row 0, so top comes to the 3rd row. Left is row 1. So the next number is (3,1).
3. Continue with top left. Top of 3 is 2, left of 1 is 3rd column. So we are in (2,3).
4. Now the top left from 2,3 is 1,2. This place is occupied, you have a 1 there. So you need to go back to original location (2,3). Then come a place down but same column. So from 2,3 we come to 3,3. Put a 4 here. Continue this way.
5. In this case the totals of rows, col and diagonal is 15. Why 15?
6. We use the natural numbers 1 to 9. Sum of 1 to 9 is n(n+1)/2. In this example we have 9x10/2=45. We have 3 rows. So we get 45/3 or 15.
sub Print(str) ' Main Program starts from here x(1,2)=1 |
- print procedure makes the printing easy.
- dim, defines an array. In this case it is an array 3 rows x 3 cols. Each value in the array is defined as 0. 1 is put then in the first row and second column.
- for loop rotates eight times for the eight numbers. a and b are the locations needed. We try top left, and if it is occupied (>0), then we go back to the original location and come one col down.
- the for loop then prints the 3 coloumns. Each row is formatted is by adding a tab (chr(9). When you compile and run this program, (magic3.vbs)
C:\scripts>magic3 //nologo C:\scripts> |
Can we make a generic version of this program. Where we can print for any odd number. Since vbscript does not allow to define an array with a variable, I have defined a large array (20,20) and allow to print a magic square. The beauty is you can pass the number as a parameter. If the parameter is even, then we add 1 and make it a odd number. The program is very similar to the previous program.
sub Print(str) sz=int(wscript.arguments(0)) x(1,(sz+1)/2)=1 |
Sample output.
C:\scripts>magicgen 5 //nologo C:\scripts>magicgen 7 //nologo |
An exercise for you. Can you use the n(n+1)/2 formula as mentioned earlier and print one line at the end of the program.
Sum of Rows/Col is _______
Like this
C:\scripts>magicgen 5 //nologo |