interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / magic-squares-of-odd-order / magic-squares-of-odd-order.om

94 lines · 1780 bytes Raw Blame History
1note Rosetta Code task "Magic squares of odd order": https://rosettacode.org/wiki/Magic_squares_of_odd_order
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text tconst "magic constant: "
8global grid ulong 81
9note emit writes every byte of a to stdout; a short write is retried, an error exits 1
10fn emit a view uchar * to void
11o = ulong 0
12while lt o len a bound 4096
13k = write 1 a o sub len a o
14if le k 0
15exit 1
16end
17o = add o ulong k
18end
19end
20note emitu writes n in decimal; 20 digits hold every ulong
21fn emitu n ulong to void
22d = new uchar 20 0
23i = ulong 20
24v = n
25while true bound 20
26i = sub i 1
27put d i uchar add rem v 10 48
28v = div v 10
29if eq v 0
30break
31end
32end
33emit part d i sub 20 i
34end
35note emitw writes n right-aligned in w columns (w at most 20; a wider number is not cut)
36fn emitw n ulong w ulong to void
37d = new uchar 20 32
38i = ulong 20
39v = n
40while true bound 20
41i = sub i 1
42put d i uchar add rem v 10 48
43v = div v 10
44if eq v 0
45break
46end
47end
48if gt w sub 20 i
49i = sub 20 w
50end
51emit part d i sub 20 i
52end
53note the Siamese method: 1 goes in the middle of the top row; each next number goes one up and one
54note right (wrapping round), or straight down when that cell is taken, which happens every n numbers
55fn siamese n ulong to void
56for i ulong mul n n
57put grid i 0
58end
59r = ulong 0
60c = div n 2
61for k ulong mul n n
62put grid add mul r n c add k 1
63ur = rem sub add r n 1 n
64uc = rem add c 1 n
65if eq get grid add mul ur n uc 0
66r = ur
67c = uc
68else
69r = rem add r 1 n
70end
71end
72end
73fn show n ulong to void
74for i ulong n
75for j ulong n
76emitw get grid add mul i n j 4
77end
78emit nl
79end
80emit tconst
81emitu div mul n add mul n n 1 2
82emit nl
83end
84fn main to int
85siamese 3
86show 3
87emit nl
88siamese 5
89show 5
90emit nl
91siamese 9
92show 9
93ret 0
94end