omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / zig-zag-matrix / zig-zag-matrix.om
| 1 | note Rosetta Code task "Zig-zag matrix": https://rosettacode.org/wiki/Zig-zag_matrix |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text minus "-" |
| 7 | global grid ulong 64 |
| 8 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 9 | fn emit a view uchar * to void |
| 10 | o = ulong 0 |
| 11 | while lt o len a bound 4096 |
| 12 | k = write 1 a o sub len a o |
| 13 | if le k 0 |
| 14 | exit 1 |
| 15 | end |
| 16 | o = add o ulong k |
| 17 | end |
| 18 | end |
| 19 | note emitu writes n in decimal; 20 digits hold every ulong |
| 20 | fn emitu n ulong to void |
| 21 | d = new uchar 20 0 |
| 22 | i = ulong 20 |
| 23 | v = n |
| 24 | while true bound 20 |
| 25 | i = sub i 1 |
| 26 | put d i uchar add rem v 10 48 |
| 27 | v = div v 10 |
| 28 | if eq v 0 |
| 29 | break |
| 30 | end |
| 31 | end |
| 32 | emit part d i sub 20 i |
| 33 | end |
| 34 | note emitw writes n right-aligned in w columns (w at most 20; a wider number is not cut) |
| 35 | fn emitw n ulong w ulong to void |
| 36 | d = new uchar 20 32 |
| 37 | i = ulong 20 |
| 38 | v = n |
| 39 | while true bound 20 |
| 40 | i = sub i 1 |
| 41 | put d i uchar add rem v 10 48 |
| 42 | v = div v 10 |
| 43 | if eq v 0 |
| 44 | break |
| 45 | end |
| 46 | end |
| 47 | if gt w sub 20 i |
| 48 | i = sub 20 w |
| 49 | end |
| 50 | emit part d i sub 20 i |
| 51 | end |
| 52 | note number the cells along the anti-diagonals d = i + j; even diagonals run up and to the right |
| 53 | note (i falling), odd ones down and to the left (i rising) |
| 54 | fn zigzag n ulong to void |
| 55 | k = ulong 0 |
| 56 | for d ulong sub mul n 2 1 |
| 57 | for x ulong add d 1 |
| 58 | i = x |
| 59 | if eq rem d 2 0 |
| 60 | i = sub d x |
| 61 | end |
| 62 | if and lt i n le sub d i sub n 1 |
| 63 | put grid add mul i n sub d i k |
| 64 | k = add k 1 |
| 65 | end |
| 66 | end |
| 67 | end |
| 68 | end |
| 69 | fn show n ulong to void |
| 70 | for i ulong n |
| 71 | for j ulong n |
| 72 | emitw get grid add mul i n j 3 |
| 73 | end |
| 74 | emit nl |
| 75 | end |
| 76 | end |
| 77 | fn main to int |
| 78 | zigzag 5 |
| 79 | show 5 |
| 80 | emit nl |
| 81 | zigzag 6 |
| 82 | show 6 |
| 83 | ret 0 |
| 84 | end |