Magic squares of odd order: Difference between revisions
m
syntax highlighting fixup automation
Not a robot (talk | contribs) (Add BQN) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 38:
{{trans|Python}}
<
L(row) 1..n
print(((1..n).map(col -> @n * ((@row + col - 1 + @n I/ 2) % @n)
Line 46:
L(n) (5, 3, 7)
print("\nOrder #.\n=======".format(n))
magic(n)</
{{out}}
Line 83:
=={{header|360 Assembly}}==
{{trans|C}}
<
MAGICS CSECT
USING MAGICS,R15 set base register
Line 124:
PG DC CL92' ' buffer
YREGS
END MAGICS</
{{out}}
<pre>
Line 139:
=={{header|Ada}}==
<
procedure Magic_Square is
Line 173:
Ada.Text_IO.New_Line;
end loop;
end Magic_Square;</
{{out}}
Line 195:
=={{header|ALGOL 68}}==
<
PROC magic square = ( INT order ) [,]INT:
IF NOT ODD order OR order < 1
Line 253:
# test the magic square generation #
FOR order BY 2 TO 7 DO print square( magic square( order ) ) OD</
{{out}}
<pre>
Line 279:
=={{header|ALGOL W}}==
<
% construct a magic square of odd order - as a procedure can't return an %
% array, the caller must supply one that is big enough %
Line 355:
end for_i
end.</
{{out}}
<pre>
Line 383:
{{works with|Dyalog APL}}
{{trans|C}}
<
{{out}}
<pre> magic¨ 1 3 5 7
Line 400:
to allow for first class functions and closures.
<
-- oddMagicSquare :: Int -> [[Int]]
Line 576:
g
end if
end cond</
{{Out}}
magic(3)
Line 633:
=={{header|Arturo}}==
<
ensure -> and? odd? n
n >= 0
Line 654:
]
print ""
]</
{{out}}
Line 683:
=={{header|AutoHotkey}}==
<
msgbox % OddMagicSquare(5)
msgbox % OddMagicSquare(7)
Line 723:
return str
}
</syntaxhighlight>
{{out}}
<pre>
Line 745:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK
BEGIN {
Line 816:
printf("\t: %d diagonal bottom left to top right\n",total)
}
</syntaxhighlight>
{{out}}
<pre>
Line 854:
==={{header|Applesoft BASIC}}===
Even if the code works for any odd number, N=9 is the maximum for a 40 column wide screen. Line <code>130</code> is a user defined modulo function, and <code>140</code> helps calculate the addends for the number that will go in the current position.
<syntaxhighlight lang="applesoft basic">
100 :
110 REM MAGIC SQUARE OF ODD ORDER
Line 868:
260 NEXT I
270 PRINT "MAGIC CONSTANT: ";N * (N * N + 1) / 2
</syntaxhighlight>
{{out}}
<pre>ENTER N: 5
Line 879:
==={{header|IS-BASIC}}===
<
110 DO
120 INPUT PROMPT "The square order: ":N
Line 889:
180 PRINT
190 NEXT
200 PRINT "The magic number is:";N*(N^2+1)/2</
=={{header|Batch File}}==
<
rem Magic squares of odd order
setlocal EnableDelayedExpansion
Line 910:
set /a w=n*(n*n+1)/2
echo The magic number is: %w%
pause</
{{out}}
<pre>The square order is: 9
Line 927:
=={{header|bc}}==
{{works with|GNU bc}}
<
return(((n * n + 1) / 2) * n)
}
Line 955:
}
temp = print_magic_square(5)</
{{Out}}
Line 967:
=={{header|BCPL}}==
{{trans|C}}
<
let cell(n, x, y) = f(n, n-x-1, y)*n + f(n, x, y) + 1
Line 981:
$)
let start() be for n = 1 to 7 by 2 do magic(n)</
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 1,010:
{{trans|C}}
The size, ''n'', is specified by the first value on the stack.
<
@<$<_^#!-*:g00:,+9!%g00:+1.+1+%g00+1+*2/g00\<</
{{out}}
Line 1,022:
=={{header|BQN}}==
{{trans|C}}
<
Magic¨ ⟨1,3,5,7⟩</
{{out}}
<pre>┌─
Line 1,039:
=={{header|C}}==
Generates an associative magic square. If the size is larger than 3, the square is also [http://en.wikipedia.org/wiki/Pandiagonal_magic_square panmagic].
<
#include <stdlib.h>
Line 1,066:
return 0;
}</
{{out}}
<pre>$ ./magic 5
Line 1,078:
=={{header|C++}}==
<
#include <iostream>
#include <sstream>
Line 1,157:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,173:
=={{header|CLU}}==
<
rep = array[array[int]]
Line 1,241:
print_magic_square(n)
end
end start_up</
{{out}}
<pre>Magic square of order 1 with magic number 1:
Line 1,268:
=={{header|Common Lisp}}==
<
(loop for i from 1 to n
collect
Line 1,288:
(let* ((size (length (write-to-string (* n n))))
(format-str (format NIL "~~{~~{~~~ad~~^ ~~}~~%~~}~~%" size)))
(format T format-str (magic-square n))))</
{{Out}}
Line 1,301:
=={{header|Cowgol}}==
{{trans|C}}
<
sub magic(n: uint16) is
Line 1,339:
magic(n);
n := n + 2;
end loop;</
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 1,366:
=={{header|D}}==
{{trans|Python}}
<
{
import std.stdio, std.conv, std.range, std.algorithm, std.exception;
Line 1,389:
writeln("\nMagic constant: ", ((n * n + 1) * n) / 2);
}}</
{{out}}
<pre>17 24 1 8 15
Line 1,401:
===Alternative Version===
{{trans|C}}
<
uint[][] magicSquare(immutable uint n) pure nothrow @safe
Line 1,466:
stderr.writefln("Requires n odd and larger than 0.");
return 1;
}</
{{out}}
<pre>15 8 1 24 17
Line 1,480:
=={{header|Draco}}==
<
proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp
Line 1,550:
print_magic_square(sq5);
print_magic_square(sq7)
corp</
{{out}}
<pre>Magic square of order 1 with magic number 1:
Line 1,578:
=={{header|EchoLisp}}==
The '''make-ms''' procedure allows to construct different magic squares for a same n, by modifying the grid filling moves. (see MathWorld reference)
<
(lib 'matrix)
Line 1,611:
(array-print ms))
</syntaxhighlight>
{{out}}
<pre>
Line 1,660:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def odd_magic_square(n) when rem(n,2)==1 do
for i <- 0..n-1 do
Line 1,677:
IO.puts "\nSize #{n}, magic sum #{div(n*n+1,2)*n}"
RC.odd_magic_square(n) |> RC.print_square
end)</
{{out}}
Line 1,708:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MAGIC_SQUARE
Line 1,802:
END PROGRAM
</syntaxhighlight>
{{out}}
Same as FreeBasic version
Line 1,822:
=={{header|Factor}}==
This solution uses the method from the paper linked in the J entry: http://www.jsoftware.com/papers/eem/magicsq.htm
<
sequences sequences.extras ;
IN: rosetta-code.magic-squares-odd
Line 1,839:
"Magic number: %d\n\n" printf ;
3 5 11 [ show-square ] tri@</
{{out}}
<pre>
Line 1,873:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,902:
f2 = n * (1 + n * n) / 2
end function
end program</
Output:
<pre>Magic Square Order: 15
Line 1,924:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,017:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>Odd magic square size: 5 * 5 Odd magic square size: 11 * 11
Line 2,036:
=={{header|Frink}}==
This program takes an order from command-line or requests an odd order from the user. It uses an algorithm from Dr. Crypton's column in Science Digest in the 1980s which the developer of Frink remembered and used to use by hand to create giant magic squares until his English teacher told him "don't do that in class."
<
until isInteger[order] and order mod 2 == 1
order = eval[input["Enter order (must be odd): ", 3]]
Line 2,059:
println[formatTable[a]]
println["Magic number is " + sum[a@0]]</
{{out}}
<pre>
Line 2,072:
=={{header|Go}}==
{{trans|C}}
<
import (
Line 2,111:
fmt.Println()
}
}</
{{out}}
<pre>
Line 2,123:
====Translating imperative code====
{{trans|cpp}}
<
import Data.List
Line 2,184:
putStr " = "
putStrLn $ show $ magicSum x
putStrLn $ display $ magicNumber x</
====Transpose . cycled====
Line 2,190:
Defining the magic square as two applications of ('''transpose . cycled''') to a simply ordered square.
<
import Data.List (maximumBy, transpose)
import Data.List.Split (chunksOf)
Line 2,237:
<*> succ . maximum . fmap length . join
)
$ fmap show <$> rows</
{{Out}}
<pre> 8 1 6
Line 2,260:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
<
import Control.Monad (forM_)
Line 2,352:
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn ""</
{{Out}}
<pre>8 1 6
Line 2,381:
This is a Unicon-specific solution because of the use of the <tt>[: ... :]</tt> construct.
<
n := integer(!A) | 3
write("Magic number: ",n*(n*n+1)/2)
Line 2,405:
s := *(n*n)+2
every r := !sq do every writes(right(!r,s)|"\n")
end</
{{out}}
Line 2,423:
Based on http://www.jsoftware.com/papers/eem/magicsq.htm
<
In other words, generate a square of counting integers, like this:
<
1 2 3
4 5 6
7 8 9</
Then generate a list of integers centering on 0 up to half of that value, like this:
<
_1 0 1</
Finally, rotate each corresponding row and column of the table by the corresponding value in the list. We can use the same instructions to rotate both rows and columns if we transpose the matrix before rotating (and perform this transpose+rotate twice).
Line 2,439:
Example use:
<
9 15 16 22 3
20 21 2 8 14
Line 2,448:
65
~.+/ms 101
515201</
Note also that an important feature of magic squares is that their diagonals sum the same way:
Line 2,458:
=={{header|Java}}==
<
public static void main(String[] args) {
Line 2,504:
return grid;
}
}</
{{out}}
Line 2,521:
( and referring to http://www.jsoftware.com/papers/eem/magicsq.htm )
<
// n -> [[n]]
Line 2,606:
}
).join('\n\n')
})();</
Output:
Line 2,668:
(2nd Haskell version: ''cycledRows . transpose . cycledRows'')
<
// magicSquare :: Int -> [[Int]]
Line 2,740:
.map(magicSquare)
.map(xs => unlines(xs.map(show))));
})();</
{{Out}}
<pre>[8,1,6]
Line 2,763:
Encoding the traditional [[wp:Siamese_method|'Siamese' method]]
{{Trans|Haskell}}
<
// Number of rows -> n rows of integers
Line 2,929:
n => unlines(table(" ",
map(xs => map(show, xs), oddMagicTable(n))))));
})();</
{{Out}}
<pre>8 1 6
Line 2,951:
=={{header|jq}}==
'''Adapted from [[#AWK]]'''
<
if type != "number" or . % 2 == 0 or . <= 0
then error("odd_magic_square requires an odd positive integer")
Line 2,965:
else [ (($x+$n-1) % $n), (($y+$n+1) % $n), .]
end ) | .[2]
end ;</
'''Examples'''
<
def pp: if length == 0 then empty
else "\(.[0])", (.[1:] | pp )
Line 2,975:
;
(3, 5, 9) | task</
{{out}}
<
The magic sum for a square of size 3 is 15:
[8,1,6]
Line 2,997:
[26,28,39,50,61,72,74,4,15]
[36,38,49,60,71,73,3,14,25]
[37,48,59,70,81,2,13,24,35]</
=={{header|Julia}}==
<
function magicsquareodd(base::Int)
Line 3,033:
end
println()
end</
{{out}}
Line 3,062:
=={{header|Kotlin}}==
{{trans|C}}
<
fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n
Line 3,080:
}
println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
}</
Sample input/output:
{{out}}
Line 3,100:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
Dim m(1,1)
Line 3,150:
End If
End Sub
</syntaxhighlight>
{{Out}}
<pre>
Line 3,207:
Rotate rows and columns of the initial matrix with rows filled in order 1 2 3 .... N^2
Method from http://www.jsoftware.com/papers/eem/magicsq.htm
<
rho[m_] := MapIndexed[rp, m];
magic[n_] :=
Line 3,213:
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]]</
{{out}}
(alignment lost in translation to text):
Line 3,245:
=={{header|Maxima}}==
<
wrap(P):=maplist('wrap1, P);
Line 3,261:
Pc: uprigth(P),
if M[Pc[1],Pc[2]]=0 then P: Pc
else while(M[P[1],P[2]]#0) do P: down(P)));</
Usage:
<
[ 8 1 6 ]
[ ]
Line 3,296:
/* magic number for n=7 */
(%i9) lsum(q, q, first(magic(7)));
(%o9) 175</
=={{header|Nim}}==
{{trans|Python}}
<
proc magic(n: int) =
Line 3,314:
for n in [3, 5, 7]:
echo "\nOrder ", n, "\n======="
magic(n)</
{{out}}
Line 3,349:
=={{header|Oforth}}==
<
| i j wd |
n sq log asInteger 1+ ->wd
Line 3,360:
printcr
]
System.Out "Magic constant is : " << n sq 1 + 2 / n * << cr ;</
{{out}}
Line 3,376:
{{trans|Perl}}
The index-fiddling differs from Perl since GP vectors start at 1.
<
my(M=matrix(n,n),j=n\2+1,i=1);
for(l=1,n^2,
Line 3,389:
M;
}
magicSquare(7)</
{{out}}
<pre>[30 39 48 1 10 19 28]
Line 3,408:
{{works with|Free Pascal|1.0}}
{{trans|C}}
<
(* Magic squares of odd order *)
CONST
Line 3,423:
END;
WRITELN('The magic number is: ',n*(n*n+1) DIV 2)
END (*magic*).</
{{out}}
<pre>
Line 3,441:
shuffles columns and rows and changed col<-> row to get different looks. n! x n! * 2 different arrangements.
See last column of version before moved to the top row.
<
{$IFDEF FPC }{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 3,538:
Mq := MagicSqrOdd(n,random(2)=0);
writeln(MagicSqrCheck(Mq));
end.</
{{out}}
<pre>
Line 3,558:
See [[Magic_squares/Perl|Magic squares/Perl]] for a general magic square generator.
<syntaxhighlight lang
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">magic_square</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 3,594:
<span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #000000;">square</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,622:
{{Trans|J}}
<
go =>
Line 3,708:
nl
end,
nl.</
{{out}}
Line 3,753:
===Testing a larger instance===
<
N = 313,
M = magic_square(N),
check(M),
nl.</
{{out}}
Line 3,764:
=={{header|PicoLisp}}==
<
(de magic (A)
(let
Line 3,792:
(magic 5)
(prinl)
(magic 7)</
{{out}}
<pre>
Line 3,813:
=={{header|PL/I}}==
<
declare n fixed binary;
Line 3,850:
put skip list ('The magic number is' || sum(m(1,*)));
end;
end magic;</
{{out}}
<pre>What is the order of the magic square?
Line 3,875:
=={{header|PureBasic}}==
{{trans|Pascal}}
<
Define.i i,j
Line 3,888:
PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2))
EndIf
Input()</
{{out}}
<pre>
Line 3,906:
=={{header|Python}}==
===Procedural===
<
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
Line 3,950:
All sum to magic number 175
>>> </
===Composition of pure functions===
Line 3,956:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<
from itertools import cycle, islice, repeat
Line 4,143:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Magic squares of odd order N:
Line 4,169:
=={{header|QB64}}==
<
'$Dynamic
DefLng A-Z
Line 4,223:
Next row
End If
End Sub</
{{Out}}
<pre>Order 5 Magic Square constant is 65
Line 4,264:
=={{header|Racket}}==
<
;; Using "helpful formulae" in:
;; http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order
Line 4,296:
(displayln (show-magic-square 3))
(displayln (show-magic-square 5))
(displayln (show-magic-square 9))</
{{out}}
<pre>MAGIC SQUARE ORDER:3
Line 4,363:
=={{header|REXX}}==
This REXX version will also generate a square of an even order, but it'll not be a ''magic square''.
<
parse arg N . /*obtain the optional argument from CL.*/
if N=='' | N=="," then N=5 /*Not specified? Then use the default.*/
Line 4,385:
say /* [↓] If an odd square, show magic #.*/
if N//2 then say 'The magic number (or magic constant is): ' N * (NN+1) % 2
/*stick a fork in it, we're all done. */</
{{out|output|text= when using the default input of: '''5'''}}
<pre>
Line 4,430:
=={{header|Ring}}==
<
n=9
see "the square order is : " + n + nl
Line 4,441:
next
see "the magic number is : " + n*(n*n+1) / 2 + nl
</syntaxhighlight>
Output:
<pre>
Line 4,460:
=={{header|Ruby}}==
<
raise ArgumentError "Need odd positive number" if n.even? || n <= 0
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
Line 4,470:
odd_magic_square(n).each{|row| puts fmt % row}
end
</syntaxhighlight>
{{out}}
<pre>
Line 4,498:
=={{header|Rust}}==
<
let n = 9;
let mut square = vec![vec![0; n]; n];
Line 4,510:
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
}</
{{out}}
Line 4,525:
=={{header|Scala}}==
<
require(n % 2 != 0, "n must be an odd number")
Line 4,584:
printMagicSquare(7)
}</
{{out}}
Line 4,604:
=={{header|Seed7}}==
<
const func integer: succ (in integer: num, in integer: max) is
Line 4,640:
writeln;
end for;
end func;</
{{out}}
Line 4,656:
=={{header|Sidef}}==
<
var i = 0
var j = int(n/2)
Line 4,687:
print_square(sq)
say "\nThe magic number is: #{sq[0].sum}"</
{{out}}
Line 4,715:
=={{header|Swift}}==
<
struct Point: CustomStringConvertible {
Line 4,873:
try MagicSquare(base: 7).createOdd()
</syntaxhighlight>
Demonstrating:
{{works with|Swift 5}}
Line 4,912:
=={{header|Tcl}}==
<
if {!($order & 1) || $order < 0} {
error "order must be odd and positive"
Line 4,929:
}
return $s
}</
Demonstrating:
{{works with|Tcl|8.6}}
<
set square [magicSquare 5]
puts [join [lmap row $square {join [lmap n $row {format "%2s" $n}]}] "\n"]
puts "magic number = [tcl::mathop::+ {*}[lindex $square 0]]"</
{{out}}
<pre>
Line 4,950:
{{trans|C}}
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
<
DelVar [A]:{N,N}→dim([A])
For(I,1,N)
Line 4,957:
End
End
[A]</
{{out}}
<pre>
Line 4,973:
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
Proc _magicsq(5)
Line 5,036:
Print
Return
</syntaxhighlight>
{{out}}
<pre>Odd magic square size: 5 * 5
Line 5,069:
{{trans|C}}
Works with Excel VBA.
<
'Magic squares of odd order
Const n = 9
Line 5,081:
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub 'magicsquare
</syntaxhighlight>
=={{header|VBScript}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="vb">
Sub magic_square(n)
Dim ms()
Line 5,125:
magic_square(5)
</syntaxhighlight>
{{Out}}
Line 5,139:
{{trans|C}}
{{works with|Visual Basic|VB6 Standard}}
<
'Magic squares of odd order
Const n = 9
Line 5,153:
Debug.Print "The magic number is: " & n * (n * n + 1) \ 2
End Sub 'magicsquare
</syntaxhighlight>
{{out}}
<pre>
Line 5,171:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<
'Magic squares of odd order
Const n = 9
Line 5,184:
Next i
Console.WriteLine("The magic number is: " & n * (n * n + 1) \ 2)
End Sub 'magicsquare</
{{out}}
<pre>
Line 5,202:
=={{header|VTL-2}}==
{{trans|C}}
<
20 ?="Magic square of order ";
30 ?=N
Line 5,219:
160 ?=""
170 N=N+2
180 #=7>N*20</
{{out}}
<pre>Magic square of order 1 with constant 1:
Line 5,248:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var ms = Fn.new { |n|
Line 5,278:
System.print()
}
System.print("\nMagic number : %(((n*n + 1)/2).floor * n)")</
{{out}}
Line 5,293:
=={{header|zkl}}==
{{trans|Ruby}}
<
fcn odd_magic_square(n){ //-->list of n*n numbers, row order
if (n.isEven or n <= 0) throw(Exception.ValueError("Need odd positive number"));
Line 5,303:
fmt := "%%%dd".fmt((n*n).toString().len() + 1) * n;
odd_magic_square(n).pump(Console.println,T(Void.Read,n-1),fmt.fmt);
});</
{{out}}
<pre>
|