Jump to content

Gray code: Difference between revisions

m (→‎{{header|Wren}}: Minor tidy)
Line 3,381:
30 11110 10001 30
31 11111 10000 31
</pre>
 
=={{header|jq}}==
{{works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
 
The following is slightly more verbose than it need be but for the
sake of jaq.
<syntaxhighlight lang="jq">
def encode:
def flip: if . == 1 then 0 else 1 end;
. as $b
| reduce range(1; length) as $i ($b;
if $b[$i-1] == 1 then .[$i] |= flip
else .
end ) ;
 
def decode:
def xor($a;$b): ($a + $b) % 2;
. as $g
| reduce range(1; length) as $i (.[:1];
.[$i] = xor($g[$i]; .[$i-1]) ) ;
 
 
# input: a non-negative integer
# output: a binary array, least-significant bit first
def to_binary:
if . == 0 then [0]
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2]
| .[:-1] # remove the uninteresting 0
end ;
 
def lpad($len; $fill):
tostring
| ($len - length) as $l
| if $l <= 0 then .
else ($fill * $l)[:$l] + .
end;
 
def pp: map(tostring) | join("") | lpad(5; "0");
 
### The task
"decimal binary gray roundtrip",
(range(0; 32) as $i
| ($i | to_binary | reverse) as $b
| ($b|encode) as $g
| " \($i|lpad(2;" ")) \($b|pp) \($g|pp) \($g|decode == $b)" )
</syntaxhighlight>
{{output}}
<pre>
decimal binary gray roundtrip
0 00000 00000 true
1 00001 00001 true
2 00010 00011 true
3 00011 00010 true
4 00100 00110 true
5 00101 00111 true
6 00110 00101 true
7 00111 00100 true
8 01000 01100 true
9 01001 01101 true
10 01010 01111 true
11 01011 01110 true
12 01100 01010 true
13 01101 01011 true
14 01110 01001 true
15 01111 01000 true
16 10000 11000 true
17 10001 11001 true
18 10010 11011 true
19 10011 11010 true
20 10100 11110 true
21 10101 11111 true
22 10110 11101 true
23 10111 11100 true
24 11000 10100 true
25 11001 10101 true
26 11010 10111 true
27 11011 10110 true
28 11100 10010 true
29 11101 10011 true
30 11110 10001 true
31 11111 10000 true
</pre>
 
2,442

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.