Skip to content

Instantly share code, notes, and snippets.

@IainNZ
Created August 25, 2014 18:03
Show Gist options
  • Save IainNZ/9b5f1eb1bcf923ed02d9 to your computer and use it in GitHub Desktop.
Save IainNZ/9b5f1eb1bcf923ed02d9 to your computer and use it in GitHub Desktop.
magic squars
function iain_magic(n::Int)
if n % 2 == 1
# Odd-order magic square
# http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order
M = zeros(Int, n, n)
for I = 1:n, J = 1:n # row, column
@inbounds M[I,J] = n*((I+J-1+div(n,2))%n) + ((I+2J-2)%n) + 1
end
return M
elseif n % 4 == 0
# Doubly-even order magic square
# http://en.wikipedia.org/wiki/Magic_square#A_method_of_constructing_a_magic_square_of_doubly_even_order
# http://hal.archives-ouvertes.fr/docs/00/94/51/29/PDF/magicsquarev2.pdf
M = [(i-1)*n+j for i = 1:n, j = 1:n]
for outer_col = 1:4:n, outer_row = 1:4:n
# Sides
for i in (1,2), j in (0,3)
@inbounds M[outer_row+i,outer_col+j] = n^2 - M[outer_row+i,outer_col+j]
end
# Top and bottom
for i in (0,3), j in (1,2)
@inbounds M[outer_row+i,outer_col+j] = n^2 - M[outer_row+i,outer_col+j]
end
end
return M
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment