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 / pancake-sort / pancake-sort.om

127 lines · 2335 bytes Raw Blame History
1note Rosetta Code task "Sorting algorithms/Pancake sort": https://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text data "23 -7 61 4 0 38 15 -7 90 2 11"
8text tflips "flips: "
9global vals long 16
10note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11fn emit a view uchar * to void
12o = ulong 0
13while lt o len a bound 4096
14k = write 1 a o sub len a o
15if le k 0
16exit 1
17end
18o = add o ulong k
19end
20end
21note emitu writes n in decimal; 20 digits hold every ulong
22fn emitu n ulong to void
23d = new uchar 20 0
24i = ulong 20
25v = n
26while true bound 20
27i = sub i 1
28put d i uchar add rem v 10 48
29v = div v 10
30if eq v 0
31break
32end
33end
34emit part d i sub 20 i
35end
36note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
37fn emiti n long to void
38if lt n 0
39emit minus
40emitu add bitcast ulong not n 1
41else
42emitu ulong n
43end
44end
45note parse reads the decimal numbers in s (separated by spaces, an optional - sign) into vals and
46note returns how many; one pass over s, so the loop is bounded by len s
47fn parse s view uchar * to ulong
48n = ulong 0
49v = long 0
50sg = long 1
51dig = false
52for i ulong len s
53c = get s i
54if eq c 45
55sg = long -1
56else
57if and ge c 48 le c 57
58v = add mul v 10 long sub c 48
59dig = true
60else
61if dig
62put vals n mul sg v
63n = add n 1
64end
65v = long 0
66sg = long 1
67dig = false
68end
69end
70end
71if dig
72put vals n mul sg v
73n = add n 1
74end
75ret n
76end
77note show writes vals[0..n-1] separated by spaces, then a newline
78fn show n ulong to void
79for i ulong n
80if gt i 0
81emit sp
82end
83emiti get vals i
84end
85emit nl
86end
87note flip reverses vals[0..k-1]; k/2 swaps
88fn flip k ulong to void
89for i ulong shr k 1
90t = get vals i
91put vals i get vals sub sub k i 1
92put vals sub sub k i 1 t
93end
94end
95note pksort brings the largest of vals[0..s-1] to the front, then flips it to position s-1, for s = n .. 2;
96note it returns the number of flips made, at most 2*(n-1)
97fn pksort n ulong to ulong
98f = ulong 0
99for x ulong sub n 1
100s = sub n x
101m = ulong 0
102for i ulong s
103if gt get vals i get vals m
104m = i
105end
106end
107if ne m sub s 1
108if ne m 0
109flip add m 1
110f = add f 1
111end
112flip s
113f = add f 1
114end
115end
116ret f
117end
118fn main to int
119n = parse data
120show n
121f = pksort n
122show n
123emit tflips
124emitu f
125emit nl
126ret 0
127end