omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / combinations / combinations.om
| 1 | note Rosetta Code task "Combinations": https://rosettacode.org/wiki/Combinations |
| 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 tcount "combinations: " |
| 8 | global comb ulong 8 |
| 9 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 10 | fn emit a view uchar * to void |
| 11 | o = ulong 0 |
| 12 | while lt o len a bound 4096 |
| 13 | k = write 1 a o sub len a o |
| 14 | if le k 0 |
| 15 | exit 1 |
| 16 | end |
| 17 | o = add o ulong k |
| 18 | end |
| 19 | end |
| 20 | note emitu writes n in decimal; 20 digits hold every ulong |
| 21 | fn emitu n ulong to void |
| 22 | d = new uchar 20 0 |
| 23 | i = ulong 20 |
| 24 | v = n |
| 25 | while true bound 20 |
| 26 | i = sub i 1 |
| 27 | put d i uchar add rem v 10 48 |
| 28 | v = div v 10 |
| 29 | if eq v 0 |
| 30 | break |
| 31 | end |
| 32 | end |
| 33 | emit part d i sub 20 i |
| 34 | end |
| 35 | note nextc steps comb[0..k-1] to the next k-subset of 0..n-1 in lexicographic order: raise the last |
| 36 | note element that can still rise and reset the ones after it; false after the last subset |
| 37 | fn nextc k ulong n ulong to bool |
| 38 | i = k |
| 39 | while gt i 0 bound 8 |
| 40 | i = sub i 1 |
| 41 | if lt get comb i add sub n k i |
| 42 | put comb i add get comb i 1 |
| 43 | for x ulong sub sub k i 1 |
| 44 | j = add add i x 1 |
| 45 | put comb j add get comb sub j 1 1 |
| 46 | end |
| 47 | ret true |
| 48 | end |
| 49 | end |
| 50 | ret false |
| 51 | end |
| 52 | fn show k ulong to void |
| 53 | for i ulong k |
| 54 | if gt i 0 |
| 55 | emit sp |
| 56 | end |
| 57 | emitu get comb i |
| 58 | end |
| 59 | emit nl |
| 60 | end |
| 61 | note 5 choose 3 is 10, which bounds the loop |
| 62 | fn main to int |
| 63 | k = ulong 3 |
| 64 | for i ulong k |
| 65 | put comb i i |
| 66 | end |
| 67 | c = ulong 1 |
| 68 | show k |
| 69 | while nextc k 5 bound 10 |
| 70 | show k |
| 71 | c = add c 1 |
| 72 | end |
| 73 | emit tcount |
| 74 | emitu c |
| 75 | emit nl |
| 76 | ret 0 |
| 77 | end |