interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / si / rosetta / tasks / permutations-by-swapping / permutations-by-swapping.om

111 lines · 2207 bytes Raw Blame History
1note Rosetta Code task "Permutations by swapping": https://rosettacode.org/wiki/Permutations_by_swapping
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text tperm "Perm: ["
8text tsign "] Sign: "
9text tcomma ", "
10global perm ulong 8
11global dir long 8
12note emit writes every byte of a to stdout; a short write is retried, an error exits 1
13fn emit a view uchar * to void
14o = ulong 0
15while lt o len a bound 4096
16k = write 1 a o sub len a o
17if le k 0
18exit 1
19end
20o = add o ulong k
21end
22end
23note emitu writes n in decimal; 20 digits hold every ulong
24fn emitu n ulong to void
25d = new uchar 20 0
26i = ulong 20
27v = n
28while true bound 20
29i = sub i 1
30put d i uchar add rem v 10 48
31v = div v 10
32if eq v 0
33break
34end
35end
36emit part d i sub 20 i
37end
38note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
39fn emiti n long to void
40if lt n 0
41emit minus
42emitu add bitcast ulong not n 1
43else
44emitu ulong n
45end
46end
47note Steinhaus-Johnson-Trotter with Even's speedup: every element has a direction (all start left);
48note the largest mobile element (one whose neighbour in its direction is smaller) swaps that way, and
49note every larger element turns round; each step is one swap, so the sign alternates
50fn mobile n ulong to ulong
51b = n
52for i ulong n
53j = add long i get dir i
54if and ge j 0 lt j long n
55if gt get perm i get perm ulong j
56if or eq b n gt get perm i get perm b
57b = i
58end
59end
60end
61end
62ret b
63end
64fn show n ulong s long to void
65emit tperm
66for i ulong n
67if gt i 0
68emit tcomma
69end
70emitu get perm i
71end
72emit tsign
73emiti s
74emit nl
75end
76fn sjt n ulong to void
77for i ulong n
78put perm i add i 1
79put dir i -1
80end
81s = long 1
82show n s
83note each pass makes one new permutation and n! of them end the run: 720 = 6! covers n up to 6
84while true bound 720
85m = mobile n
86if eq m n
87break
88end
89v = get perm m
90j = ulong add long m get dir m
91put perm m get perm j
92put perm j v
93t = get dir m
94put dir m get dir j
95put dir j t
96for i ulong n
97if gt get perm i v
98put dir i neg get dir i
99end
100end
101s = neg s
102show n s
103end
104end
105note n = 3 and n = 4: 3! + 4! = 30 lines; 6! = 720 bounds the loop for any n up to 6
106fn main to int
107sjt 3
108emit nl
109sjt 4
110ret 0
111end