omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / combinations-with-repetitions / combinations-with-repetitions.om
| 1 | note Rosetta Code task "Combinations with repetitions": https://rosettacode.org/wiki/Combinations_with_repetitions |
| 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 t0 "iced" |
| 8 | text t1 "jam" |
| 9 | text t2 "plain" |
| 10 | text tcount "choices of 3 from 10 kinds: " |
| 11 | global pick ulong 4 |
| 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 nextm steps pick[0..k-1], a non-decreasing list of kinds 0..n-1, to the next one in lexicographic |
| 39 | note order: raise the last pick below n-1 and set every pick after it to the same kind |
| 40 | fn nextm k ulong n ulong to bool |
| 41 | i = k |
| 42 | while gt i 0 bound 4 |
| 43 | i = sub i 1 |
| 44 | if lt get pick i sub n 1 |
| 45 | v = add get pick i 1 |
| 46 | for x ulong sub k i |
| 47 | put pick add i x v |
| 48 | end |
| 49 | ret true |
| 50 | end |
| 51 | end |
| 52 | ret false |
| 53 | end |
| 54 | fn kind d ulong to void |
| 55 | if eq d 0 |
| 56 | emit t0 |
| 57 | end |
| 58 | if eq d 1 |
| 59 | emit t1 |
| 60 | end |
| 61 | if eq d 2 |
| 62 | emit t2 |
| 63 | end |
| 64 | end |
| 65 | fn main to int |
| 66 | note the two-doughnut choices from three kinds: C(3+2-1, 2) = 6 |
| 67 | put pick 0 0 |
| 68 | put pick 1 0 |
| 69 | while true bound 6 |
| 70 | kind get pick 0 |
| 71 | emit sp |
| 72 | kind get pick 1 |
| 73 | emit nl |
| 74 | if not nextm 2 3 |
| 75 | break |
| 76 | end |
| 77 | end |
| 78 | note counted, not computed: C(10+3-1, 3) = 220 choices bound the loop |
| 79 | put pick 0 0 |
| 80 | put pick 1 0 |
| 81 | put pick 2 0 |
| 82 | c = ulong 1 |
| 83 | while nextm 3 10 bound 220 |
| 84 | c = add c 1 |
| 85 | end |
| 86 | emit tcount |
| 87 | emitu c |
| 88 | emit nl |
| 89 | ret 0 |
| 90 | end |