omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / recamans-sequence / recamans-sequence.om
| 1 | note Rosetta Code task "Recaman's sequence": https://rosettacode.org/wiki/Recaman%27s_sequence |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text first "first 15 terms:" |
| 7 | text dup "first term already seen: a(" |
| 8 | text eqs ") = " |
| 9 | text cov "terms a(0)..a(n) first contain every integer 0..1000 at n = " |
| 10 | note sn v is 1 once v has appeared; the oracle's run shows no term before 0..1000 is covered exceeds 1942300 |
| 11 | global sn uchar 1942301 |
| 12 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 13 | fn emit a view uchar * to void |
| 14 | o = ulong 0 |
| 15 | while lt o len a bound 4096 |
| 16 | k = write 1 a o sub len a o |
| 17 | if le k 0 |
| 18 | exit 1 |
| 19 | end |
| 20 | o = add o ulong k |
| 21 | end |
| 22 | end |
| 23 | note emitu writes n in decimal; 20 digits hold every ulong |
| 24 | fn emitu n ulong to void |
| 25 | d = new uchar 20 0 |
| 26 | i = ulong 20 |
| 27 | v = n |
| 28 | while true bound 20 |
| 29 | i = sub i 1 |
| 30 | put d i uchar add rem v 10 48 |
| 31 | v = div v 10 |
| 32 | if eq v 0 |
| 33 | break |
| 34 | end |
| 35 | end |
| 36 | emit part d i sub 20 i |
| 37 | end |
| 38 | note a(0) = 0; a(n) = a(n-1) - n if that is positive and new, else a(n-1) + n |
| 39 | note bound: the cover is complete at n = 328002, below the 999999 loop bound |
| 40 | fn main to int |
| 41 | emit first |
| 42 | emit sp |
| 43 | emitu 0 |
| 44 | put sn 0 1 |
| 45 | a = ulong 0 |
| 46 | n = ulong 0 |
| 47 | d = ulong 0 |
| 48 | c = ulong 1 |
| 49 | while lt c 1001 bound 999999 |
| 50 | n = add n 1 |
| 51 | nw = add a n |
| 52 | if gt a n |
| 53 | if eq get sn sub a n 0 |
| 54 | nw = sub a n |
| 55 | end |
| 56 | end |
| 57 | a = nw |
| 58 | if eq get sn a 0 |
| 59 | if le a 1000 |
| 60 | c = add c 1 |
| 61 | end |
| 62 | else |
| 63 | if eq d 0 |
| 64 | d = n |
| 65 | emit nl |
| 66 | emit dup |
| 67 | emitu n |
| 68 | emit eqs |
| 69 | emitu a |
| 70 | emit nl |
| 71 | end |
| 72 | end |
| 73 | put sn a 1 |
| 74 | if lt n 15 |
| 75 | emit sp |
| 76 | emitu a |
| 77 | end |
| 78 | end |
| 79 | emit cov |
| 80 | emitu n |
| 81 | emit nl |
| 82 | ret 0 |
| 83 | end |