omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / hailstone-sequence / hailstone-sequence.om
| 1 | note Rosetta Code task "Hailstone sequence": https://rosettacode.org/wiki/Hailstone_sequence |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text t1 "hailstone(27) has " |
| 7 | text t2 " elements:" |
| 8 | text dots " ..." |
| 9 | text t3 "below 100000 the longest is " |
| 10 | text t4 " with " |
| 11 | text t5 " elements\n" |
| 12 | global seq ulong 1000 |
| 13 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 14 | fn emit a view uchar * to void |
| 15 | o = ulong 0 |
| 16 | while lt o len a bound 4096 |
| 17 | k = write 1 a o sub len a o |
| 18 | if le k 0 |
| 19 | exit 1 |
| 20 | end |
| 21 | o = add o ulong k |
| 22 | end |
| 23 | end |
| 24 | note emitu writes n in decimal; 20 digits hold every ulong |
| 25 | fn emitu n ulong to void |
| 26 | d = new uchar 20 0 |
| 27 | i = ulong 20 |
| 28 | v = n |
| 29 | while true bound 20 |
| 30 | i = sub i 1 |
| 31 | put d i uchar add rem v 10 48 |
| 32 | v = div v 10 |
| 33 | if eq v 0 |
| 34 | break |
| 35 | end |
| 36 | end |
| 37 | emit part d i sub 20 i |
| 38 | end |
| 39 | note hfill stores the sequence from n in seq and returns its length; every start below 100000 |
| 40 | note reaches 1 in at most 351 elements, so 999 steps is a proof-backed bound (more traps 4) |
| 41 | fn hfill n ulong to ulong |
| 42 | c = ulong 1 |
| 43 | v = n |
| 44 | put seq 0 v |
| 45 | while ne v 1 bound 999 |
| 46 | if eq rem v 2 0 |
| 47 | v = div v 2 |
| 48 | else |
| 49 | v = add mul v 3 1 |
| 50 | end |
| 51 | put seq c v |
| 52 | c = add c 1 |
| 53 | end |
| 54 | ret c |
| 55 | end |
| 56 | fn main to int |
| 57 | c = hfill 27 |
| 58 | emit t1 |
| 59 | emitu c |
| 60 | emit t2 |
| 61 | for i ulong 4 |
| 62 | emit sp |
| 63 | emitu get seq i |
| 64 | end |
| 65 | emit dots |
| 66 | for i ulong 4 |
| 67 | emit sp |
| 68 | emitu get seq add sub c 4 i |
| 69 | end |
| 70 | emit nl |
| 71 | best = ulong 1 |
| 72 | bl = ulong 1 |
| 73 | for i ulong 99999 |
| 74 | n = add i 1 |
| 75 | l = hfill n |
| 76 | if gt l bl |
| 77 | bl = l |
| 78 | best = n |
| 79 | end |
| 80 | end |
| 81 | emit t3 |
| 82 | emitu best |
| 83 | emit t4 |
| 84 | emitu bl |
| 85 | emit t5 |
| 86 | ret 0 |
| 87 | end |