Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-rosetta/blob/main/tasks/gray-code/gray-code.om # omega-rosetta aien-dev/omega-rosetta Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-rosetta / tasks / gray-code / gray-code.om` 94 lines ยท 1679 bytes Raw Blame History 1 note Rosetta Code task "Gray code": https://rosettacode.org/wiki/Gray_code 2 note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 om2 4 text nl "\n" 5 text sp " " 6 text minus "-" 7 text thead "number binary gray decoded\n" 8 note emit writes every byte of a to stdout; a short write is retried, an error exits 1 9 fn emit a view uchar * to void 10 o = ulong 0 11 while lt o len a bound 4096 12 k = write 1 a o sub len a o 13 if le k 0 14 exit 1 15 end 16 o = add o ulong k 17 end 18 end 19 note emitu writes n in decimal; 20 digits hold every ulong 20 fn emitu n ulong to void 21 d = new uchar 20 0 22 i = ulong 20 23 v = n 24 while true bound 20 25 i = sub i 1 26 put d i uchar add rem v 10 48 27 v = div v 10 28 if eq v 0 29 break 30 end 31 end 32 emit part d i sub 20 i 33 end 34 note emitw writes n right-aligned in w columns (w at most 20; a wider number is not cut) 35 fn emitw n ulong w ulong to void 36 d = new uchar 20 32 37 i = ulong 20 38 v = n 39 while true bound 20 40 i = sub i 1 41 put d i uchar add rem v 10 48 42 v = div v 10 43 if eq v 0 44 break 45 end 46 end 47 if gt w sub 20 i 48 i = sub 20 w 49 end 50 emit part d i sub 20 i 51 end 52 note bin5 writes the low 5 bits of v, most significant first 53 fn bin5 v ulong to void 54 d = new uchar 5 48 55 for i ulong 5 56 if ne and shr v sub 4 i 1 0 57 put d i 49 58 end 59 end 60 emit d 61 end 62 note encode is n xor (n >> 1); decode undoes it by xoring in every right shift of g 63 fn encode n ulong to ulong 64 ret xor n shr n 1 65 end 66 note one xor per bit of g: a ulong has 64, so 64 shifts empty s 67 fn decode g ulong to ulong 68 n = g 69 s = shr g 1 70 while ne s 0 bound 64 71 n = xor n s 72 s = shr s 1 73 end 74 ret n 75 end 76 fn main to int 77 emit thead 78 for n ulong 32 79 g = encode n 80 emitw n 6 81 emit sp 82 emit sp 83 bin5 n 84 emit sp 85 emit sp 86 emit sp 87 bin5 g 88 emit sp 89 emit sp 90 emitw decode g 7 91 emit nl 92 end 93 ret 0 94 end