interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / drafts / rosettacode / gray-code.wiki

124 lines · 2538 bytes Raw Blame History
1=={{header|Omegese}}==
2{{works with|omc|sha256 2c824805, aien-dev/omega-mv e5b32567, Linux AArch64}}
3Omega has no imports, so the small output helpers (<code>emit</code> and friends) are part of the program.
4<syntaxhighlight lang="text">
5om2
6text nl "\n"
7text sp " "
8text minus "-"
9text thead "number binary gray decoded\n"
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 emitw writes n right-aligned in w columns (w at most 20; a wider number is not cut)
37fn emitw n ulong w ulong to void
38d = new uchar 20 32
39i = ulong 20
40v = n
41while true bound 20
42i = sub i 1
43put d i uchar add rem v 10 48
44v = div v 10
45if eq v 0
46break
47end
48end
49if gt w sub 20 i
50i = sub 20 w
51end
52emit part d i sub 20 i
53end
54note bin5 writes the low 5 bits of v, most significant first
55fn bin5 v ulong to void
56d = new uchar 5 48
57for i ulong 5
58if ne and shr v sub 4 i 1 0
59put d i 49
60end
61end
62emit d
63end
64note encode is n xor (n >> 1); decode undoes it by xoring in every right shift of g
65fn encode n ulong to ulong
66ret xor n shr n 1
67end
68note one xor per bit of g: a ulong has 64, so 64 shifts empty s
69fn decode g ulong to ulong
70n = g
71s = shr g 1
72while ne s 0 bound 64
73n = xor n s
74s = shr s 1
75end
76ret n
77end
78fn main to int
79emit thead
80for n ulong 32
81g = encode n
82emitw n 6
83emit sp
84emit sp
85bin5 n
86emit sp
87emit sp
88emit sp
89bin5 g
90emit sp
91emit sp
92emitw decode g 7
93emit nl
94end
95ret 0
96end
97</syntaxhighlight>
98{{out}}
99<pre>
100number binary gray decoded
101 0 00000 00000 0
102 1 00001 00001 1
103 2 00010 00011 2
104 3 00011 00010 3
105 4 00100 00110 4
106 5 00101 00111 5
107 6 00110 00101 6
108 7 00111 00100 7
109 8 01000 01100 8
110 9 01001 01101 9
111 10 01010 01111 10
112 11 01011 01110 11
113 12 01100 01010 12
114 13 01101 01011 13
115...
116 24 11000 10100 24
117 25 11001 10101 25
118 26 11010 10111 26
119 27 11011 10110 27
120 28 11100 10010 28
121 29 11101 10011 29
122 30 11110 10001 30
123 31 11111 10000 31
124</pre>