Magic squares of odd order: Difference between revisions
Content added Content deleted
m (→{{header|Java}}: remove redundant import) |
|||
Line 24: | Line 24: | ||
;Also see: |
;Also see: |
||
* MathWorld™ entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] |
* MathWorld™ entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] |
||
=={{header|Ada}}== |
|||
<lang Ada>with Ada.Text_IO, Ada.Command_Line; |
|||
procedure Magic_Square is |
|||
N: constant Positive := Positive'Value(Ada.Command_Line.Argument(1)); |
|||
subtype Constants is Natural range 1 .. N*N; |
|||
package CIO is new Ada.Text_IO.Integer_IO(Constants); |
|||
Undef: constant Natural := 0; |
|||
subtype Index is Natural range 0 .. N-1; |
|||
function Inc(I: Index) return Index is (if I = N-1 then 0 else I+1); |
|||
function Dec(I: Index) return Index is (if I = 0 then N-1 else I-1); |
|||
A: array(Index, Index) of Natural := (others => (others => Undef)); |
|||
-- initially undefined; at the end holding the magic square |
|||
X: Index := 0; Y: Index := N/2; -- start position for the algorithm |
|||
begin |
|||
for I in Constants loop -- write 1, 2, ..., N*N into the magic array |
|||
A(X, Y) := I; -- write I into the magic array |
|||
if A(Dec(X), Inc(Y)) = Undef then |
|||
X := Dec(X); Y := Inc(Y); -- go right-up |
|||
else |
|||
X := Inc(X); -- go down |
|||
end if; |
|||
end loop; |
|||
for Row in Index loop -- output the magic array |
|||
for Collumn in Index loop |
|||
CIO.Put(A(Row, Collumn), |
|||
Width => (if N*N < 10 then 2 elsif N*N < 100 then 3 else 4)); |
|||
end loop; |
|||
Ada.Text_IO.New_Line; |
|||
end loop; |
|||
end Magic_Square;</lang> |
|||
{{out}} |
|||
<pre>>./magic_square 3 |
|||
8 1 6 |
|||
3 5 7 |
|||
4 9 2 |
|||
>./magic_square 11 |
|||
68 81 94 107 120 1 14 27 40 53 66 |
|||
80 93 106 119 11 13 26 39 52 65 67 |
|||
92 105 118 10 12 25 38 51 64 77 79 |
|||
104 117 9 22 24 37 50 63 76 78 91 |
|||
116 8 21 23 36 49 62 75 88 90 103 |
|||
7 20 33 35 48 61 74 87 89 102 115 |
|||
19 32 34 47 60 73 86 99 101 114 6 |
|||
31 44 46 59 72 85 98 100 113 5 18 |
|||
43 45 58 71 84 97 110 112 4 17 30 |
|||
55 57 70 83 96 109 111 3 16 29 42 |
|||
56 69 82 95 108 121 2 15 28 41 54</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |