interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / counting-sort / counting-sort.om

117 lines · 2190 bytes Raw Blame History
1note Rosetta Code task "Sorting algorithms/Counting sort": https://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text data "7 -3 12 0 7 4 -3 9 15 1 -5 4 12 0 8"
8global vals long 16
9global cnt ulong 64
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 cntsort counts each value in min..max (the range must fit the 64 counters), then rewrites vals
88fn cntsort n ulong to void
89lo = get vals 0
90hi = get vals 0
91for i ulong n
92if lt get vals i lo
93lo = get vals i
94end
95if gt get vals i hi
96hi = get vals i
97end
98end
99for i ulong n
100c = ulong sub get vals i lo
101put cnt c add get cnt c 1
102end
103k = ulong 0
104for x ulong add ulong sub hi lo 1
105for y ulong get cnt x
106put vals k add lo long x
107k = add k 1
108end
109end
110end
111fn main to int
112n = parse data
113show n
114cntsort n
115show n
116ret 0
117end