interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / dutch-national-flag-problem / dutch-national-flag-problem.om

131 lines · 2368 bytes Raw Blame History
1note Rosetta Code task "Dutch national flag problem": https://rosettacode.org/wiki/Dutch_national_flag_problem
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text tred "red"
8text twhite "white"
9text tblue "blue"
10text tok "in flag order: "
11text tyes "yes\n"
12text tno "no\n"
13global vals long 16
14global seed ulong 1
15note emit writes every byte of a to stdout; a short write is retried, an error exits 1
16fn emit a view uchar * to void
17o = ulong 0
18while lt o len a bound 4096
19k = write 1 a o sub len a o
20if le k 0
21exit 1
22end
23o = add o ulong k
24end
25end
26note emitu writes n in decimal; 20 digits hold every ulong
27fn emitu n ulong to void
28d = new uchar 20 0
29i = ulong 20
30v = n
31while true bound 20
32i = sub i 1
33put d i uchar add rem v 10 48
34v = div v 10
35if eq v 0
36break
37end
38end
39emit part d i sub 20 i
40end
41note rnd is Knuth's MMIX linear congruential generator, x = x*6364136223846793005 + 1442695040888963407
42note mod 2^64 (ulong arithmetic wraps), starting from seed 0; it returns the top 31 bits, x >> 33
43fn rnd to ulong
44x = add mul get seed 0 6364136223846793005 1442695040888963407
45put seed 0 x
46ret shr x 33
47end
48fn ball c long to void
49if eq c 0
50emit tred
51end
52if eq c 1
53emit twhite
54end
55if eq c 2
56emit tblue
57end
58end
59fn show n ulong to void
60for i ulong n
61if gt i 0
62emit sp
63end
64ball get vals i
65end
66emit nl
67end
68fn inorder n ulong to bool
69for i ulong sub n 1
70if gt get vals i get vals add i 1
71ret false
72end
73end
74ret true
75end
76fn swap i ulong j ulong to void
77t = get vals i
78put vals i get vals j
79put vals j t
80end
81note Dijkstra's three-way partition: [0,lo) red, [lo,mid) white, (hi,n) blue; every pass moves mid up
82note or hi down, so n passes suffice
83fn flag n ulong to void
84lo = ulong 0
85mid = ulong 0
86hi = n
87while lt mid hi bound 16
88c = get vals mid
89if eq c 0
90swap lo mid
91lo = add lo 1
92mid = add mid 1
93else
94if eq c 1
95mid = add mid 1
96else
97hi = sub hi 1
98swap mid hi
99end
100end
101end
102end
103note draws 12 random balls (0 red, 1 white, 2 blue), drawing again while they happen to be in order;
104note with this generator the first draw is already out of order, and 100 draws bound it
105fn main to int
106n = ulong 12
107while true bound 100
108for i ulong n
109put vals i long rem rnd 3
110end
111if not inorder n
112break
113end
114end
115show n
116emit tok
117if inorder n
118emit tyes
119else
120emit tno
121end
122flag n
123show n
124emit tok
125if inorder n
126emit tyes
127else
128emit tno
129end
130ret 0
131end