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