Gray code: Difference between revisions

Updated to compile with Nim 1.4. Changed somewhat the presentation fo result.
m (→‎{{header|Batch File}}: less code, but slower (TnT))
(Updated to compile with Nim 1.4. Changed somewhat the presentation fo result.)
Line 3,191:
=={{header|Nim}}==
{{trans|C}}
<lang nim>proc grayEncode(n: int): autoint =
n xor (n shr 1)
 
proc grayDecode(n: int): autoint =
result = n
var t = n
Line 3,201:
result = result xor t</lang>
Demonstration code:
<lang nim>import strutils, strformat
 
for i in 0 .. 32:
echo &"{i, ":>2} => ", {toBin(grayEncode(i), 6), "} => ", {grayDecode(grayEncode(i)):>2}"</lang>
{{out}}
<pre> 0 => 000000 => 0
0 1 => 000000000001 => 0 1
1 2 => 000001000011 => 1 2
2 3 => 000011000010 => 2 3
3 4 => 000010000110 => 3 4
4 5 => 000110000111 => 4 5
5 6 => 000111000101 => 5 6
6 7 => 000101000100 => 6 7
7 8 => 000100001100 => 7 8
8 9 => 001100001101 => 8 9
9 => 001101 => 9
10 => 001111 => 10
11 => 001110 => 11
Line 3,239 ⟶ 3,238:
30 => 010001 => 30
31 => 010000 => 31
32 => 110000 => 32</pre>
</pre>
 
=={{header|OCaml}}==
Anonymous user