6
3
Create the shortest function to print a magic square of given size.
A magic square is a NxN matrix of distinct numbers and the sum of each row, column and diagonal is equal to a constant.
A magic square of size 4 is:
07 12 01 14
02 13 08 11
16 03 10 05
09 06 15 04
And the constant is 34.
The function should be able to handle inputs up to N = 30 and doesn't need to show leading zeroes.
Using Matlab's magic
function or similar built-in function is not allowed.
More useful information: http://mathworld.wolfram.com/MagicSquare.html
::Edit::
The output doesn't need to be pretty printed and may contain [](){},
or List/Array delimiters of your language. Although, it should use one line for each row
E.g.
1, 2,
3, 4,
((9,8),
(6,7))
[10 2]
[3 456]
PS: The corner case, when N = 2 is undefined behavior as there's no magic square of that size.
Also, the function should complete in less than 1 minute to avoid brute force.
Does it have to be pretty-printed, or can the function return a list of lists or similar? – Joey Adams – 2011-07-13T02:16:59.000
@Joey I Added that information – JBernardo – 2011-07-13T03:11:27.887
Bad codegolf example as it is an NP-complete problem unless you're cheating. – Neil – 2011-07-13T16:13:17.940
@Neil Reference? – Matthew Read – 2011-07-13T20:11:18.327
@JBernardo: NP-complete problems can be solved. By calling it NP-complete, I only mean there is no efficient manner of going about solving for a magic square. Though it would seem that I confused magic squares with latin squares, which is NP-complete.
– Neil – 2011-07-14T10:10:43.427@JBernardo: If you had written what I had wrote, you'd realize I was stating that I was wrong and that I confused magic squares with latin squares. Not just that, but you'd realize that NP-complete does not mean that it cannot be done since I addressed that as well. – Neil – 2011-07-14T13:02:39.047
Does the program have to handle the trivial case where N=1? – Peter Olson – 2011-07-14T13:51:50.163
@Peter Of The Corn Yes. – JBernardo – 2011-07-16T04:40:01.797