interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / gray-code / gray-code.om

94 lines · 1679 bytes Raw Blame History
1note Rosetta Code task "Gray code": https://rosettacode.org/wiki/Gray_code
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text thead "number binary gray decoded\n"
8note emit writes every byte of a to stdout; a short write is retried, an error exits 1
9fn emit a view uchar * to void
10o = ulong 0
11while lt o len a bound 4096
12k = write 1 a o sub len a o
13if le k 0
14exit 1
15end
16o = add o ulong k
17end
18end
19note emitu writes n in decimal; 20 digits hold every ulong
20fn emitu n ulong to void
21d = new uchar 20 0
22i = ulong 20
23v = n
24while true bound 20
25i = sub i 1
26put d i uchar add rem v 10 48
27v = div v 10
28if eq v 0
29break
30end
31end
32emit part d i sub 20 i
33end
34note emitw writes n right-aligned in w columns (w at most 20; a wider number is not cut)
35fn emitw n ulong w ulong to void
36d = new uchar 20 32
37i = ulong 20
38v = n
39while true bound 20
40i = sub i 1
41put d i uchar add rem v 10 48
42v = div v 10
43if eq v 0
44break
45end
46end
47if gt w sub 20 i
48i = sub 20 w
49end
50emit part d i sub 20 i
51end
52note bin5 writes the low 5 bits of v, most significant first
53fn bin5 v ulong to void
54d = new uchar 5 48
55for i ulong 5
56if ne and shr v sub 4 i 1 0
57put d i 49
58end
59end
60emit d
61end
62note encode is n xor (n >> 1); decode undoes it by xoring in every right shift of g
63fn encode n ulong to ulong
64ret xor n shr n 1
65end
66note one xor per bit of g: a ulong has 64, so 64 shifts empty s
67fn decode g ulong to ulong
68n = g
69s = shr g 1
70while ne s 0 bound 64
71n = xor n s
72s = shr s 1
73end
74ret n
75end
76fn main to int
77emit thead
78for n ulong 32
79g = encode n
80emitw n 6
81emit sp
82emit sp
83bin5 n
84emit sp
85emit sp
86emit sp
87bin5 g
88emit sp
89emit sp
90emitw decode g 7
91emit nl
92end
93ret 0
94end