interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / permutations / permutations.om

90 lines · 1638 bytes Raw Blame History
1note Rosetta Code task "Permutations": https://rosettacode.org/wiki/Permutations
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text tcount "permutations: "
8global perm ulong 8
9note emit writes every byte of a to stdout; a short write is retried, an error exits 1
10fn emit a view uchar * to void
11o = ulong 0
12while lt o len a bound 4096
13k = write 1 a o sub len a o
14if le k 0
15exit 1
16end
17o = add o ulong k
18end
19end
20note emitu writes n in decimal; 20 digits hold every ulong
21fn emitu n ulong to void
22d = new uchar 20 0
23i = ulong 20
24v = n
25while true bound 20
26i = sub i 1
27put d i uchar add rem v 10 48
28v = div v 10
29if eq v 0
30break
31end
32end
33emit part d i sub 20 i
34end
35note nextp steps perm[0..n-1] to the next permutation in lexicographic order; false after the last:
36note find the last ascent i-1 < i, swap perm[i-1] with the last larger element, reverse the tail
37fn nextp n ulong to bool
38i = sub n 1
39while gt i 0 bound 8
40if lt get perm sub i 1 get perm i
41break
42end
43i = sub i 1
44end
45if eq i 0
46ret false
47end
48j = sub n 1
49while le get perm j get perm sub i 1 bound 8
50j = sub j 1
51end
52t = get perm sub i 1
53put perm sub i 1 get perm j
54put perm j t
55k = sub n 1
56while lt i k bound 8
57t2 = get perm i
58put perm i get perm k
59put perm k t2
60i = add i 1
61k = sub k 1
62end
63ret true
64end
65fn show n ulong to void
66for i ulong n
67if gt i 0
68emit sp
69end
70emitu get perm i
71end
72emit nl
73end
74note all 4! orders of 1 2 3 4; 24 permutations bound the loop
75fn main to int
76n = ulong 4
77for i ulong n
78put perm i add i 1
79end
80c = ulong 1
81show n
82while nextp n bound 24
83show n
84c = add c 1
85end
86emit tcount
87emitu c
88emit nl
89ret 0
90end