Magic squares of odd order: Difference between revisions

Added XPL0 example.
(Magic squares of odd order in Yabasic)
(Added XPL0 example.)
Line 5,367:
 
Magic number : 65
</pre>
 
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0"> \Construct a magic square of odd order - as a procedure can't return an
\ array, the caller must supply one that is big enough.
function MagicSquare( Square, Order );
integer Square, Order;
integer Row, Col, I, J;
 
\Ensure a row/col position is on the square
function InSquare; int Pos ;
return if Pos < 1 then Order else if Pos > Order then 1 else Pos;
 
\move "up" a row in the square
function Up; int Row; return InSquare( Row - 1 );
 
\move "across right" in the square
function Right; int Col ; return InSquare( Col + 1 );
 
if (Order&1) = 0 or Order < 1 then begin
\can't make a magic square of the specified order
return false
end
else begin
\Order is OK - construct the square using de la Loubere's
\ algorithm as in the Wikipedia page
 
\initialise square
for I := 1 to Order do for J := 1 to Order do Square( I, J ) := 0;
 
\initial position is the middle of the top row
Col := ( Order + 1 ) / 2;
Row := 1;
\construct square
for I := 1 to ( Order * Order ) do begin
Square( Row, Col ) := I;
if Square( Up( Row ), Right( Col ) ) # 0 then begin
\the up/right position is already taken, move down
Row := Row + 1;
end
else begin
\can move up/right
Row := Up( Row );
Col := Right( Col );
end
end; \for_i
\sucessful result
return true
end; \magicSquare
 
\prints the magic square
procedure PrintSquare( Square, Order );
integer Square, Order;
integer Sum, W, I_W, I, J;
begin
\set integer width to accomodate the largest number in the square
W := ( Order * Order ) / 10;
I_W := 1;
while W > 0 do begin I_W := I_W + 1; W := W / 10 end;
Format(I_W+1, 0);
Sum:= 0;
for I := 1 to Order do Sum := Sum + Square( 1, I );
Text(0, "maqic square of order "); IntOut(0, Order);
Text(0, " : Sum: "); IntOut(0, Sum );
for I := 1 to Order do begin
CrLf(0);
RlOut(0, float(Square( I, 1 )) );
for J := 2 to Order do RlOut(0, float(Square( I, J )) )
end; \for_I
CrLf(0);
end; \printSquare
 
\test the magic square generation
integer Sq ( 1+11, 1+11 ), L, I;
begin
L:= [1, 3, 5, 7];
for I := 0 to 3 do begin
if MagicSquare( Sq, L(I) ) then PrintSquare( Sq, L(I) )
else Text(0, "can't generate square^m^j" );
end \for_I
end]</syntaxhighlight>
{{out}}
<pre>
maqic square of order 1 : Sum: 1
1
maqic square of order 3 : Sum: 15
8 1 6
3 5 7
4 9 2
maqic square of order 5 : Sum: 65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
maqic square of order 7 : Sum: 175
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
</pre>
 
295

edits