omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / josephus-problem / josephus-problem.om
| 1 | note Rosetta Code task "Josephus problem": https://rosettacode.org/wiki/Josephus_problem |
| 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 tkill "executed in order:" |
| 8 | text tsurv "survivor: " |
| 9 | global alive uchar 41 |
| 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 | note 41 prisoners numbered 0..40 stand in a circle; counting from 0, every 3rd one still alive is killed |
| 37 | note until one is left; each kill walks at most 3 live places, so 3*41 steps per kill bound the walk |
| 38 | fn main to int |
| 39 | n = ulong 41 |
| 40 | k = ulong 3 |
| 41 | for i ulong n |
| 42 | put alive i 1 |
| 43 | end |
| 44 | p = sub n 1 |
| 45 | emit tkill |
| 46 | for x ulong sub n 1 |
| 47 | c = ulong 0 |
| 48 | while lt c k bound 123 |
| 49 | p = rem add p 1 n |
| 50 | if eq get alive p 1 |
| 51 | c = add c 1 |
| 52 | end |
| 53 | end |
| 54 | put alive p 0 |
| 55 | emit sp |
| 56 | emitu p |
| 57 | end |
| 58 | emit nl |
| 59 | emit tsurv |
| 60 | for i ulong n |
| 61 | if eq get alive i 1 |
| 62 | emitu i |
| 63 | end |
| 64 | end |
| 65 | emit nl |
| 66 | ret 0 |
| 67 | end |