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