interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

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

121 lines · 2407 bytes Raw Blame History
1note Rosetta Code task "Sorting algorithms/Bead sort": https://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text data "5 3 1 7 4 1 1 20 0 9"
8global vals long 16
9global grid uchar 512
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 the abacus has one row per value (at most 16) and one column per unit (at most 32): grid[r*32+c]
88note holds a bead when c < vals[r]; the values here are 0 .. 20
89fn bdsort n ulong to void
90for r ulong n
91for c ulong ulong get vals r
92put grid add mul r 32 c 1
93end
94end
95note gravity: each column's beads fall to the bottom rows
96for c ulong 32
97h = ulong 0
98for r ulong n
99h = add h ulong get grid add mul r 32 c
100put grid add mul r 32 c 0
101end
102for x ulong h
103put grid add mul sub sub n x 1 32 c 1
104end
105end
106note row r now holds the r-th smallest value as its bead count, read top to bottom
107for r ulong n
108v = long 0
109for c ulong 32
110v = add v long get grid add mul r 32 c
111end
112put vals r v
113end
114end
115fn main to int
116n = parse data
117show n
118bdsort n
119show n
120ret 0
121end