omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / ethiopian-multiplication / ethiopian-multiplication.om
| 1 | note Rosetta Code task "Ethiopian multiplication": https://rosettacode.org/wiki/Ethiopian_multiplication |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text kept " KEPT\n" |
| 7 | text struck " STRUCK\n" |
| 8 | text tx " x " |
| 9 | text teq " = " |
| 10 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 11 | fn emit a view uchar * to void |
| 12 | o = ulong 0 |
| 13 | while lt o len a bound 4096 |
| 14 | k = write 1 a o sub len a o |
| 15 | if le k 0 |
| 16 | exit 1 |
| 17 | end |
| 18 | o = add o ulong k |
| 19 | end |
| 20 | end |
| 21 | note emitu writes n in decimal; 20 digits hold every ulong |
| 22 | fn emitu n ulong to void |
| 23 | d = new uchar 20 0 |
| 24 | i = ulong 20 |
| 25 | v = n |
| 26 | while true bound 20 |
| 27 | i = sub i 1 |
| 28 | put d i uchar add rem v 10 48 |
| 29 | v = div v 10 |
| 30 | if eq v 0 |
| 31 | break |
| 32 | end |
| 33 | end |
| 34 | emit part d i sub 20 i |
| 35 | end |
| 36 | fn halve n ulong to ulong |
| 37 | ret shr n 1 |
| 38 | end |
| 39 | fn double n ulong to ulong |
| 40 | ret shl n 1 |
| 41 | end |
| 42 | fn iseven n ulong to bool |
| 43 | ret eq and n 1 0 |
| 44 | end |
| 45 | note left column halves to 1, right column doubles; rows with an even left number are struck out and |
| 46 | note the kept right numbers add up to the product |
| 47 | fn ethiop a ulong b ulong to ulong |
| 48 | s = ulong 0 |
| 49 | l = a |
| 50 | r = b |
| 51 | while ge l 1 bound 64 |
| 52 | emitu l |
| 53 | emit sp |
| 54 | emitu r |
| 55 | if iseven l |
| 56 | emit struck |
| 57 | else |
| 58 | emit kept |
| 59 | s = add s r |
| 60 | end |
| 61 | l = halve l |
| 62 | r = double r |
| 63 | end |
| 64 | ret s |
| 65 | end |
| 66 | fn main to int |
| 67 | p = ethiop 17 34 |
| 68 | emitu 17 |
| 69 | emit tx |
| 70 | emitu 34 |
| 71 | emit teq |
| 72 | emitu p |
| 73 | emit nl |
| 74 | ret 0 |
| 75 | end |