Skip to content

Instantly share code, notes, and snippets.

@simonster
Last active August 29, 2015 14:05
Show Gist options
  • Save simonster/6195af68c6df33ca965d to your computer and use it in GitHub Desktop.
Save simonster/6195af68c6df33ca965d to your computer and use it in GitHub Desktop.
Magic square
function iain_magic(n::Int)
# 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+(n >> 1))%n) + ((I+2J-2)%n) + 1
end
return M
end
julia> @time for i = 1:100; iain_magic(1001); end
elapsed time: 1.716341372 seconds (801606400 bytes allocated, 12.76% gc time)
function iain_magic_32(n::Int)
# 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*(int32(I+J-1+(n >> 1))%int32(n)) + (int32(I+2J-2)%int32(n)) + 1
end
return M
end
julia> @time for i = 1:100; iain_magic_32(1001); end
elapsed time: 0.980291628 seconds (801606400 bytes allocated, 22.58% gc time)
function magic_1001()
n = 1001
# 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+(n >> 1))%n) + ((I+2J-2)%n) + 1
end
return M
end
julia> @time for i = 1:100; magic_1001(); end
elapsed time: 0.606936259 seconds (801606400 bytes allocated, 34.78% gc time)
function odd_magic(n)
M = zeros(Int, n, n)
# Odd-order magic square
# http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order
ndiv2 = div(n, 2);
for I = 1:n
intermediate1 = (I-1+ndiv2) % n
intermediate2 = (2I - 2) % n
for J = 1:n
x = ifelse(J + intermediate1 < n, J + intermediate1, J + intermediate1 - n)
y = ifelse(J + intermediate2 < n, J + intermediate2, J + intermediate2 - n)
@inbounds M[J, I] = n*x + y + 1
end
end
M
end
julia> @time for i = 1:100; odd_magic(1001); end
elapsed time: 0.481498101 seconds (801606400 bytes allocated, 45.34% gc time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment