omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / si / rosetta / tasks / permutations / permutations.om
| 1 | note Rosetta Code task "Permutations": https://rosettacode.org/wiki/Permutations |
| 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 "permutations: " |
| 8 | global perm 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 nextp steps perm[0..n-1] to the next permutation in lexicographic order; false after the last: |
| 36 | note find the last ascent i-1 < i, swap perm[i-1] with the last larger element, reverse the tail |
| 37 | fn nextp n ulong to bool |
| 38 | i = sub n 1 |
| 39 | while gt i 0 bound 8 |
| 40 | if lt get perm sub i 1 get perm i |
| 41 | break |
| 42 | end |
| 43 | i = sub i 1 |
| 44 | end |
| 45 | if eq i 0 |
| 46 | ret false |
| 47 | end |
| 48 | j = sub n 1 |
| 49 | while le get perm j get perm sub i 1 bound 8 |
| 50 | j = sub j 1 |
| 51 | end |
| 52 | t = get perm sub i 1 |
| 53 | put perm sub i 1 get perm j |
| 54 | put perm j t |
| 55 | k = sub n 1 |
| 56 | while lt i k bound 8 |
| 57 | t2 = get perm i |
| 58 | put perm i get perm k |
| 59 | put perm k t2 |
| 60 | i = add i 1 |
| 61 | k = sub k 1 |
| 62 | end |
| 63 | ret true |
| 64 | end |
| 65 | fn show n ulong to void |
| 66 | for i ulong n |
| 67 | if gt i 0 |
| 68 | emit sp |
| 69 | end |
| 70 | emitu get perm i |
| 71 | end |
| 72 | emit nl |
| 73 | end |
| 74 | note all 4! orders of 1 2 3 4; 24 permutations bound the loop |
| 75 | fn main to int |
| 76 | n = ulong 4 |
| 77 | for i ulong n |
| 78 | put perm i add i 1 |
| 79 | end |
| 80 | c = ulong 1 |
| 81 | show n |
| 82 | while nextp n bound 24 |
| 83 | show n |
| 84 | c = add c 1 |
| 85 | end |
| 86 | emit tcount |
| 87 | emitu c |
| 88 | emit nl |
| 89 | ret 0 |
| 90 | end |