Magic squares of odd order: Difference between revisions

Add CLU
(Add CLU)
Line 1,099:
22 31 40 49 2 11 20
</pre>
 
=={{header|CLU}}==
<lang clu>magic_square = cluster is create, unparse, magic_number
rep = array[array[int]]
 
create = proc (order: int) returns (cvt) signals (invalid)
if order<1 cor order//2 = 0 then signal invalid end
sq: rep := rep$fill_copy(1, order, array[int]$fill(1, order, 0))
x: int := (order+1)/2
y: int := 1
for i: int in int$from_to(1, order**2) do
sq[y][x] := i
next_x: int := inc(sq,x)
next_y: int := dec(sq,y)
if sq[next_y][next_x]=0
then x, y := next_x, next_y
else y := inc(sq,y)
end
end
return(sq)
end create
 
inc = proc (sq: rep, co: int) returns (int)
order: int := rep$size(sq)
if co=order then return(1) else return(co+1) end
end inc
 
dec = proc (sq: rep, co: int) returns (int)
order: int := rep$size(sq)
if co=1 then return(order) else return(co-1) end
end dec
unparse = proc (sq: cvt) returns (string)
order: int := rep$size(sq)
col_size: int := string$size(int$unparse(order ** 2)) + 1
ss: stream := stream$create_output()
for y: int in int$from_to(1, order) do
for x: int in int$from_to(1, order) do
stream$putright(ss, int$unparse(sq[y][x]), col_size)
end
stream$putl(ss, "")
end
return(stream$get_contents(ss))
end unparse
 
magic_number = proc (sq: cvt) returns (int)
order: int := rep$size(sq)
n: int := 0
for x: int in int$from_to(1, order) do n := n + sq[1][x] end
return(n)
end magic_number
end magic_square
 
 
print_magic_square = proc (order: int)
po: stream := stream$primary_output()
ms: magic_square := magic_square$create(order)
stream$putl(po, "Magic square of order "
|| int$unparse(order)
|| " with magic number "
|| int$unparse(magic_square$magic_number(ms))
|| ": ")
stream$putl(po, magic_square$unparse(ms))
end print_magic_square
 
start_up = proc ()
for n: int in int$from_to_by(1, 7, 2) do
print_magic_square(n)
end
end start_up</lang>
{{out}}
<pre>Magic square of order 1 with magic number 1:
1
 
Magic square of order 3 with magic number 15:
8 1 6
3 5 7
4 9 2
 
Magic square of order 5 with magic number 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
 
Magic square of order 7 with magic number 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>
 
=={{header|Common Lisp}}==
2,095

edits