Monday, November 10, 2008

Magic squares (odd size)


#!/usr/bin/python
"""This is a simple algorithm I wrote to generate
"""magic squares of odd size. Surprisingly it works

print "Type an odd number: "
dim = raw_input ()
dim = int(dim)

if dim % 2 == 0 :
dim = dim + 1
print "Not an odd number, increasing to " + str(dim)

print "Dim: " + str( dim )
mat = range(dim)
for i in range(dim):
mat[i] = range(dim)
for j in range(dim):
mat[i][j] = 0

i = 0
j = dim / 2

mat[i][j] = 1
for d in range(dim*dim - 1):
ni = (i + 1) % dim
nj = (j + 1) % dim
if mat[ni][nj] != 0 :
ni = i
nj = ( j + dim - 1 ) % dim
mat[ni][nj] = d + 2
i,j = ni,nj

print mat

-----------------
Type an odd number:
5
Dim: 5
[[13, 7, 1, 25, 19], [20, 14, 8, 2, 21], [22, 16, 15, 9, 3], [4, 23, 17, 11, 10], [6, 5, 24, 18, 12]]

0 Comments:

Post a Comment

<< Home