interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / sort-disjoint-sublist / sort-disjoint-sublist.om

134 lines · 2422 bytes Raw Blame History
1note Rosetta Code task "Sort disjoint sublist": https://rosettacode.org/wiki/Sort_disjoint_sublist
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text data "7 6 5 4 3 2 1 0"
8text tidx "indices: "
9global vals long 8
10global idx ulong 3
11global sub3 long 3
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 parse reads the decimal numbers in s (separated by spaces, an optional - sign) into vals and
48note returns how many; one pass over s, so the loop is bounded by len s
49fn parse s view uchar * to ulong
50n = ulong 0
51v = long 0
52sg = long 1
53dig = false
54for i ulong len s
55c = get s i
56if eq c 45
57sg = long -1
58else
59if and ge c 48 le c 57
60v = add mul v 10 long sub c 48
61dig = true
62else
63if dig
64put vals n mul sg v
65n = add n 1
66end
67v = long 0
68sg = long 1
69dig = false
70end
71end
72end
73if dig
74put vals n mul sg v
75n = add n 1
76end
77ret n
78end
79note show writes vals[0..n-1] separated by spaces, then a newline
80fn show n ulong to void
81for i ulong n
82if gt i 0
83emit sp
84end
85emiti get vals i
86end
87emit nl
88end
89note sorts the three indices, gathers their values, sorts those, and writes them back in index order;
90note both sorts are three compare-exchanges, enough for three elements
91fn cx3u to void
92for p ulong 3
93i = rem p 2
94if gt get idx i get idx add i 1
95t = get idx i
96put idx i get idx add i 1
97put idx add i 1 t
98end
99end
100end
101fn cx3l to void
102for p ulong 3
103i = rem p 2
104if gt get sub3 i get sub3 add i 1
105t = get sub3 i
106put sub3 i get sub3 add i 1
107put sub3 add i 1 t
108end
109end
110end
111fn main to int
112n = parse data
113put idx 0 6
114put idx 1 1
115put idx 2 7
116show n
117emit tidx
118emitu get idx 0
119emit sp
120emitu get idx 1
121emit sp
122emitu get idx 2
123emit nl
124cx3u
125for i ulong 3
126put sub3 i get vals get idx i
127end
128cx3l
129for i ulong 3
130put vals get idx i get sub3 i
131end
132show n
133ret 0
134end