Gray code: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 31: | Line 31: | ||
{{trans|Python: on integers}} |
{{trans|Python: on integers}} |
||
< |
<syntaxhighlight lang="11l">F gray_encode(n) |
||
R n (+) n >> 1 |
R n (+) n >> 1 |
||
Line 45: | Line 45: | ||
V gray = gray_encode(i) |
V gray = gray_encode(i) |
||
V dec = gray_decode(gray) |
V dec = gray_decode(gray) |
||
print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec))</ |
print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 87: | Line 87: | ||
< |
<syntaxhighlight lang="8080asm"> org 100h |
||
xra a ; set A=0 |
xra a ; set A=0 |
||
loop: push psw ; print number as decimal |
loop: push psw ; print number as decimal |
||
Line 170: | Line 170: | ||
jmp 5 |
jmp 5 |
||
arrow: db ' ==> $' |
arrow: db ' ==> $' |
||
nl: db 13,10,'$'</ |
nl: db 13,10,'$'</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 210: | Line 210: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC ToBinaryStr(BYTE n CHAR ARRAY s) |
||
BYTE i |
BYTE i |
||
Line 267: | Line 267: | ||
PrintB2(b) PutE() |
PrintB2(b) PutE() |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Gray_code.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Gray_code.png Screenshot from Atari 8-bit computer] |
||
Line 309: | Line 309: | ||
Values are implemented with 8 bits according to representation clause |
Values are implemented with 8 bits according to representation clause |
||
of Unsigned_8 (check package Interfaces). |
of Unsigned_8 (check package Interfaces). |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO, Interfaces; |
||
use Ada.Text_IO, Interfaces; |
use Ada.Text_IO, Interfaces; |
||
Line 355: | Line 355: | ||
New_Line; |
New_Line; |
||
end loop; |
end loop; |
||
end Gray;</ |
end Gray;</syntaxhighlight> |
||
Check compactness of assembly code generated by GNAT :http://pastebin.com/qtNjeQk9<br> |
Check compactness of assembly code generated by GNAT :http://pastebin.com/qtNjeQk9<br> |
||
{{out}} |
{{out}} |
||
Line 394: | Line 394: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="aime">integer |
||
gray_encode(integer n) |
gray_encode(integer n) |
||
{ |
{ |
||
Line 411: | Line 411: | ||
p; |
p; |
||
}</ |
}</syntaxhighlight> |
||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="aime">integer |
||
main(void) |
main(void) |
||
{ |
{ |
||
Line 436: | Line 436: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 0: 00000 => 00000 => 00000: 0 |
<pre> 0: 00000 => 00000 => 00000: 0 |
||
Line 473: | Line 473: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
In Algol 68 the BITS mode is specifically designed for manipulating machine words as a row of bits so it is natural to treat Gray encoded integers as values of MODE BITS. The standard operator BIN (INT) : BITS converts an INT value to a BITS value. The ABS (BITS) : INT operator performs the reverse conversion, though it has not been needed for this task. It is also natural in the language for simple operations on values to be implemented as operators, rather than as functions, as in the program below. |
In Algol 68 the BITS mode is specifically designed for manipulating machine words as a row of bits so it is natural to treat Gray encoded integers as values of MODE BITS. The standard operator BIN (INT) : BITS converts an INT value to a BITS value. The ABS (BITS) : INT operator performs the reverse conversion, though it has not been needed for this task. It is also natural in the language for simple operations on values to be implemented as operators, rather than as functions, as in the program below. |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
OP GRAY = (BITS b) BITS : b XOR (b SHR 1); CO Convert to Gray code CO |
OP GRAY = (BITS b) BITS : b XOR (b SHR 1); CO Convert to Gray code CO |
||
OP YARG = (BITS g) BITS : CO Convert from Gray code CO |
OP YARG = (BITS g) BITS : CO Convert from Gray code CO |
||
Line 484: | Line 484: | ||
printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i)) |
printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i)) |
||
OD |
OD |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 0: 00000 >= 00000 >= 00000 |
<pre> 0: 00000 >= 00000 >= 00000 |
||
Line 523: | Line 523: | ||
{{trans|C}} |
{{trans|C}} |
||
Version: Hopper-BASIC. |
Version: Hopper-BASIC. |
||
<syntaxhighlight lang="amazing hopper"> |
|||
<lang Amazing Hopper> |
|||
#proto GrayEncode(_X_) |
#proto GrayEncode(_X_) |
||
#synon _GrayEncode *getGrayEncode |
#synon _GrayEncode *getGrayEncode |
||
Line 555: | Line 555: | ||
Wend |
Wend |
||
Return (p) |
Return (p) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 596: | Line 596: | ||
Generate the complete N-bit Gray sequence as a matrix:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0A%28%7B%280%2C%u2375%29%u236A1%2C%u2296%u2375%7D%u2363N%29%281%200%u2374%u236C%29,run=1 run]</sup> |
Generate the complete N-bit Gray sequence as a matrix:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0A%28%7B%280%2C%u2375%29%u236A1%2C%u2296%u2375%7D%u2363N%29%281%200%u2374%u236C%29,run=1 run]</sup> |
||
< |
<syntaxhighlight lang="apl">N←5 |
||
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)</ |
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">0 0 0 0 0 |
<pre style="overflow: auto; height: 20em;">0 0 0 0 0 |
||
Line 633: | Line 633: | ||
Encode and decode an individual integer:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0AgrayEncode%u2190%7Ba%u2260N%u2191%280%2Ca%u2190%28N%u23742%29%u22A4%u2375%29%7D%0AgrayDecode%u2190%7B2%u22A5%u2260%u233FN%20N%u2191N%282%D7N%29%u2374%u2375%2C0%2CN%u23740%7D%0A%0AgrayEncode%2019,run=1 run]</sup> |
Encode and decode an individual integer:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0AgrayEncode%u2190%7Ba%u2260N%u2191%280%2Ca%u2190%28N%u23742%29%u22A4%u2375%29%7D%0AgrayDecode%u2190%7B2%u22A5%u2260%u233FN%20N%u2191N%282%D7N%29%u2374%u2375%2C0%2CN%u23740%7D%0A%0AgrayEncode%2019,run=1 run]</sup> |
||
< |
<syntaxhighlight lang="apl">N←5 |
||
grayEncode←{a≠N↑(0,a←(N⍴2)⊤⍵)} |
grayEncode←{a≠N↑(0,a←(N⍴2)⊤⍵)} |
||
grayDecode←{2⊥≠⌿N N↑N(2×N)⍴⍵,0,N⍴0} |
grayDecode←{2⊥≠⌿N N↑N(2×N)⍴⍵,0,N⍴0} |
||
grayEncode 19</ |
grayEncode 19</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 1 0 1 0</pre> |
<pre>1 1 0 1 0</pre> |
||
Line 643: | Line 643: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">toGray: function [n]-> xor n shr n 1 |
||
fromGray: function [n][ |
fromGray: function [n][ |
||
p: n |
p: n |
||
Line 664: | Line 664: | ||
pad to :string decoded 2 |
pad to :string decoded 2 |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 702: | Line 702: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="ahk">gray_encode(n){ |
||
return n ^ (n >> 1) |
return n ^ (n >> 1) |
||
} |
} |
||
Line 724: | Line 724: | ||
n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n)) |
n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n)) |
||
. " => " BinString(gray_decode(e)) " => " BinString(n) "`n" |
. " => " BinString(gray_decode(e)) " => " BinString(n) "`n" |
||
MsgBox % clipboard := out</ |
MsgBox % clipboard := out</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">0 : 00000 => 00000 => 00000 => 00000 |
<pre style="overflow: auto; height: 20em;">0 : 00000 => 00000 => 00000 => 00000 |
||
Line 760: | Line 760: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk"># Tested using GAWK |
||
function bits2str(bits, data, mask) |
function bits2str(bits, data, mask) |
||
Line 796: | Line 796: | ||
for (i=0; i < 32; i++) |
for (i=0; i < 32; i++) |
||
printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i))) |
printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i))) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 => 00000 => 00000 => 00000 |
<pre>0 => 00000 => 00000 => 00000 |
||
Line 832: | Line 832: | ||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos">:: Gray Code Task from Rosetta Code |
||
:: Batch File Implementation |
:: Batch File Implementation |
||
Line 893: | Line 893: | ||
echo(%%n -^> !bin! -^> !gray! -^> !rebin! |
echo(%%n -^> !bin! -^> !gray! -^> !rebin! |
||
) |
) |
||
exit /b 0</ |
exit /b 0</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre style="overflow: auto; height: 20em;"># -> bin -> enc -> dec |
<pre style="overflow: auto; height: 20em;"># -> bin -> enc -> dec |
||
Line 931: | Line 931: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB" |
||
PRINT " Decimal Binary Gray Decoded" |
PRINT " Decimal Binary Gray Decoded" |
||
Line 945: | Line 945: | ||
DEF FNgraydecode(G%) : LOCAL B% |
DEF FNgraydecode(G%) : LOCAL B% |
||
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0 |
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0 |
||
= B%</ |
= B%</syntaxhighlight> |
||
=={{header|bc}}== |
=={{header|bc}}== |
||
This language has no bitwise logic. We must repeat, with each bit, the exclusive-or calculation. This solution uses <tt>h % 2</tt> and <tt>i % 2</tt> to grab the low bits, and repeats <tt>if (h % 2 != i % 2)</tt> to check if the exclusive-or is one. Our encoding and decoding functions are identical except that <tt>h</tt> always comes from the decoded integer. |
This language has no bitwise logic. We must repeat, with each bit, the exclusive-or calculation. This solution uses <tt>h % 2</tt> and <tt>i % 2</tt> to grab the low bits, and repeats <tt>if (h % 2 != i % 2)</tt> to check if the exclusive-or is one. Our encoding and decoding functions are identical except that <tt>h</tt> always comes from the decoded integer. |
||
< |
<syntaxhighlight lang="bc">scale = 0 /* to use integer division */ |
||
/* encode Gray code */ |
/* encode Gray code */ |
||
Line 995: | Line 995: | ||
" |
" |
||
} |
} |
||
quit</ |
quit</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,033: | Line 1,033: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans|Tcl}} |
{{trans|Tcl}} |
||
< |
<syntaxhighlight lang="c">int gray_encode(int n) { |
||
return n ^ (n >> 1); |
return n ^ (n >> 1); |
||
} |
} |
||
Line 1,041: | Line 1,041: | ||
while (n >>= 1) p ^= n; |
while (n >>= 1) p ^= n; |
||
return p; |
return p; |
||
}</ |
}</syntaxhighlight> |
||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
/* Simple bool formatter, only good on range 0..31 */ |
/* Simple bool formatter, only good on range 0..31 */ |
||
Line 1,066: | Line 1,066: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,104: | Line 1,104: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="c sharp">using System; |
||
public class Gray { |
public class Gray { |
||
Line 1,126: | Line 1,126: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,165: | Line 1,165: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <bitset> |
#include <bitset> |
||
#include <iostream> |
#include <iostream> |
||
Line 1,203: | Line 1,203: | ||
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; |
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,242: | Line 1,242: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
gray_encode = (n) -> |
gray_encode = (n) -> |
||
n ^ (n >> 1) |
n ^ (n >> 1) |
||
Line 1,253: | Line 1,253: | ||
for i in [0..32] |
for i in [0..32] |
||
console.log gray_decode gray_encode(i) |
console.log gray_decode gray_encode(i) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun gray-encode (n) |
||
(logxor n (ash n -1))) |
(logxor n (ash n -1))) |
||
Line 1,266: | Line 1,266: | ||
(loop for i to 31 do |
(loop for i to 31 do |
||
(let* ((g (gray-encode i)) (b (gray-decode g))) |
(let* ((g (gray-encode i)) (b (gray-decode g))) |
||
(format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b)))</ |
(format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,306: | Line 1,306: | ||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE GrayCodes; |
MODULE GrayCodes; |
||
IMPORT StdLog,SYSTEM; |
IMPORT StdLog,SYSTEM; |
||
Line 1,358: | Line 1,358: | ||
END GrayCodes. |
END GrayCodes. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^QGrayCodes.Do<br/> |
Execute: ^QGrayCodes.Do<br/> |
||
{{out}} |
{{out}} |
||
Line 1,401: | Line 1,401: | ||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="ruby"> |
||
def gray_encode(bin) |
def gray_encode(bin) |
||
bin ^ (bin >> 1) |
bin ^ (bin >> 1) |
||
Line 1,414: | Line 1,414: | ||
bin |
bin |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="ruby"> |
||
(0..31).each do |n| |
(0..31).each do |n| |
||
gr = gray_encode n |
gr = gray_encode n |
||
Line 1,422: | Line 1,422: | ||
printf "%2d : %05b => %05b => %05b : %2d\n", n, n, gr, bin, bin |
printf "%2d : %05b => %05b => %05b : %2d\n", n, n, gr, bin, bin |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,460: | Line 1,460: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">uint grayEncode(in uint n) pure nothrow @nogc { |
||
return n ^ (n >> 1); |
return n ^ (n >> 1); |
||
} |
} |
||
Line 1,481: | Line 1,481: | ||
assert(d == n); |
assert(d == n); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> N N2 enc dec2 dec |
<pre> N N2 enc dec2 dec |
||
Line 1,523: | Line 1,523: | ||
then the decode table is calculated and appended. |
then the decode table is calculated and appended. |
||
Same output. |
Same output. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm; |
||
T[] gray(int N : 1, T)() pure nothrow { |
T[] gray(int N : 1, T)() pure nothrow { |
||
Line 1,560: | Line 1,560: | ||
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded); |
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Short Functional-Style Generator=== |
===Short Functional-Style Generator=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
string[] g(in uint n) pure nothrow { |
string[] g(in uint n) pure nothrow { |
||
Line 1,573: | Line 1,573: | ||
void main() { |
void main() { |
||
4.g.writeln; |
4.g.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>["0000", "0001", "0011", "0010", "0110", "0111", "0101", "0100", "1100", "1101", "1111", "1110", "1010", "1011", "1001", "1000"]</pre> |
<pre>["0000", "0001", "0011", "0010", "0110", "0111", "0101", "0100", "1100", "1101", "1111", "1110", "1010", "1011", "1001", "1000"]</pre> |
||
Line 1,579: | Line 1,579: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{trans|DWScript}} |
{{trans|DWScript}} |
||
< |
<syntaxhighlight lang="delphi">program GrayCode; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 1,623: | Line 1,623: | ||
Writeln(Format(' %2d %s %s %s %2d', [i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d])); |
Writeln(Format(' %2d %s %s %s %2d', [i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d])); |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,663: | Line 1,663: | ||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">function Encode(v : Integer) : Integer; |
||
begin |
begin |
||
Result := v xor (v shr 1); |
Result := v xor (v shr 1); |
||
Line 1,685: | Line 1,685: | ||
PrintLn(Format(' %2d %s %s %s %2d', |
PrintLn(Format(' %2d %s %s %s %2d', |
||
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d])); |
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d])); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang="elixir">defmodule Gray_code do |
||
use Bitwise |
use Bitwise |
||
def encode(n), do: bxor(n, bsr(n,1)) |
def encode(n), do: bxor(n, bsr(n,1)) |
||
Line 1,703: | Line 1,703: | ||
d = Gray_code.decode(g) |
d = Gray_code.decode(g) |
||
:io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B : ~2B~n", [n, n, g, d, d]) |
:io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B : ~2B~n", [n, n, g, d, d]) |
||
end)</ |
end)</syntaxhighlight> |
||
output is the same as "Erlang". |
output is the same as "Erlang". |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
{{trans|Euphoria}} |
{{trans|Euphoria}} |
||
< |
<syntaxhighlight lang="erlang">-module(gray). |
||
-export([encode/1, decode/1]). |
-export([encode/1, decode/1]). |
||
Line 1,717: | Line 1,717: | ||
decode(0,N) -> N; |
decode(0,N) -> N; |
||
decode(G,N) -> decode(G bsr 1, G bxor N). |
decode(G,N) -> decode(G bsr 1, G bxor N). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="erlang">-module(testgray). |
||
test_encode(N) -> |
test_encode(N) -> |
||
Line 1,730: | Line 1,730: | ||
test_encode(I, N) when I < N -> test_encode(I), test_encode(I+1, N). |
test_encode(I, N) when I < N -> test_encode(I), test_encode(I+1, N). |
||
main(_) -> test_encode(0,32).</ |
main(_) -> test_encode(0,32).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,769: | Line 1,769: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function gray_encode(integer n) |
||
return xor_bits(n,floor(n/2)) |
return xor_bits(n,floor(n/2)) |
||
end function |
end function |
||
Line 1,802: | Line 1,802: | ||
j = gray_decode(j) |
j = gray_decode(j) |
||
printf(1,"%05d\n",dcb(j)) |
printf(1,"%05d\n",dcb(j)) |
||
end for</ |
end for</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,840: | Line 1,840: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
===The Function=== |
===The Function=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// Functıons to translate bınary to grey code and vv. Nigel Galloway: December 7th., 2018 |
// Functıons to translate bınary to grey code and vv. Nigel Galloway: December 7th., 2018 |
||
let grayCode,invGrayCode=let fN g (n:uint8)=n^^^(n>>>g) in ((fN 1),(fN 1>>fN 2>>fN 4)) |
let grayCode,invGrayCode=let fN g (n:uint8)=n^^^(n>>>g) in ((fN 1),(fN 1>>fN 2>>fN 4)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===The Task=== |
===The Task=== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
[0uy..31uy]|>List.iter(fun n->let g=grayCode n in printfn "%2d -> %5s (%2d) -> %2d" n (System.Convert.ToString(g,2)) g (invGrayCode g))</ |
[0uy..31uy]|>List.iter(fun n->let g=grayCode n in printfn "%2d -> %5s (%2d) -> %2d" n (System.Convert.ToString(g,2)) g (invGrayCode g))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,885: | Line 1,885: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Translation of C. |
Translation of C. |
||
< |
<syntaxhighlight lang="factor">USING: math.ranges locals ; |
||
IN: rosetta-gray |
IN: rosetta-gray |
||
Line 1,901: | Line 1,901: | ||
MAIN: main |
MAIN: main |
||
</syntaxhighlight> |
|||
</lang> |
|||
Running above code prints: |
Running above code prints: |
||
< |
<syntaxhighlight lang="factor">{ -1 "-1" "0" 0 } |
||
{ 0 "0" "0" 0 } |
{ 0 "0" "0" 0 } |
||
{ 1 "1" "1" 1 } |
{ 1 "1" "1" 1 } |
||
Line 1,936: | Line 1,936: | ||
{ 30 "11110" "10001" 30 } |
{ 30 "11110" "10001" 30 } |
||
{ 31 "11111" "10000" 31 } |
{ 31 "11111" "10000" 31 } |
||
{ 32 "100000" "110000" 32 }</ |
{ 32 "100000" "110000" 32 }</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 1,942: | Line 1,942: | ||
These functions take input parameters from the stack and return the result on the stack. |
These functions take input parameters from the stack and return the result on the stack. |
||
< |
<syntaxhighlight lang="forth">: >gray ( n -- n' ) dup 2/ xor ; \ n' = n xor (n logically right shifted 1 time) |
||
\ 2/ is Forth divide by 2, ie: shift right 1 |
\ 2/ is Forth divide by 2, ie: shift right 1 |
||
: gray> ( n -- n ) |
: gray> ( n -- n ) |
||
Line 1,963: | Line 1,963: | ||
loop |
loop |
||
decimal ; \ revert to BASE 10 |
decimal ; \ revert to BASE 10 |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,002: | Line 2,002: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Using [http://www.everyspec.com/MIL-STD/MIL-STD+(1700+-+1799)/download.php?spec=MIL-STD-1753.011044.PDF MIL-STD-1753] extensions in '''Fortran 77''', and formulas found at OEIS for [[oeis:A003188|direct]] and [[oeis:A006068|inverse]] Gray code : |
Using [http://www.everyspec.com/MIL-STD/MIL-STD+(1700+-+1799)/download.php?spec=MIL-STD-1753.011044.PDF MIL-STD-1753] extensions in '''Fortran 77''', and formulas found at OEIS for [[oeis:A003188|direct]] and [[oeis:A006068|inverse]] Gray code : |
||
< |
<syntaxhighlight lang="fortran"> PROGRAM GRAY |
||
IMPLICIT NONE |
IMPLICIT NONE |
||
INTEGER IGRAY,I,J,K |
INTEGER IGRAY,I,J,K |
||
Line 2,047: | Line 2,047: | ||
10 CONTINUE |
10 CONTINUE |
||
S(1:L-K)='' |
S(1:L-K)='' |
||
END</ |
END</syntaxhighlight> |
||
<pre> 0 : 00000 => 00000 => 00000 : 0 |
<pre> 0 : 00000 => 00000 => 00000 : 0 |
||
Line 2,083: | Line 2,083: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' version 18-01-2017 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
Line 2,123: | Line 2,123: | ||
Print : Print "hit any key to end program" |
Print : Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> i binary gray gra2bin |
<pre> i binary gray gra2bin |
||
Line 2,162: | Line 2,162: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
Frink has built-in functions to convert to and from binary reflected Gray code. |
Frink has built-in functions to convert to and from binary reflected Gray code. |
||
< |
<syntaxhighlight lang="frink"> |
||
for i=0 to 31 |
for i=0 to 31 |
||
{ |
{ |
||
Line 2,169: | Line 2,169: | ||
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)] |
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)] |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|Euphoria}} |
{{trans|Euphoria}} |
||
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read. |
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,196: | Line 2,196: | ||
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) |
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,236: | Line 2,236: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def grayEncode = { i -> |
||
i ^ (i >>> 1) |
i ^ (i >>> 1) |
||
} |
} |
||
Line 2,245: | Line 2,245: | ||
def h = grayDecode(code >>> 1) |
def h = grayDecode(code >>> 1) |
||
return (h << 1) + ((code ^ h) & 1) |
return (h << 1) + ((code ^ h) & 1) |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">def binary = { i, minBits = 1 -> |
||
def remainder = i |
def remainder = i |
||
def bin = [] |
def bin = [] |
||
Line 2,268: | Line 2,268: | ||
it, iB[4],iB[3],iB[2],iB[1],iB[0], cB[4],cB[3],cB[2],cB[1],cB[0], decode) |
it, iB[4],iB[3],iB[2],iB[1],iB[0], cB[4],cB[3],cB[2],cB[1],cB[0], decode) |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
Results: |
Results: |
||
Line 2,309: | Line 2,309: | ||
For zero padding, replace the %5s specifiers in the format string with %05s. |
For zero padding, replace the %5s specifiers in the format string with %05s. |
||
< |
<syntaxhighlight lang="haskell">import Data.Bits |
||
import Data.Char |
import Data.Char |
||
import Numeric |
import Numeric |
||
Line 2,331: | Line 2,331: | ||
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray |
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray |
||
main = forM_ [0..31::Int] showGrayCode</ |
main = forM_ [0..31::Int] showGrayCode</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
The following works in both languages: |
The following works in both languages: |
||
< |
<syntaxhighlight lang="unicon">link bitint |
||
procedure main() |
procedure main() |
||
Line 2,353: | Line 2,353: | ||
every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1" |
every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1" |
||
return b |
return b |
||
end</ |
end</syntaxhighlight> |
||
Sample run: |
Sample run: |
||
Line 2,376: | Line 2,376: | ||
<code>G2B</code> is an invertible function which will translate Gray code to Binary: |
<code>G2B</code> is an invertible function which will translate Gray code to Binary: |
||
< |
<syntaxhighlight lang="j">G2B=: ~:/\&.|:</syntaxhighlight> |
||
Thus <code>G2B inv</code> will translate binary to Gray code. |
Thus <code>G2B inv</code> will translate binary to Gray code. |
||
Line 2,382: | Line 2,382: | ||
Required example: |
Required example: |
||
< |
<syntaxhighlight lang="j"> n=:i.32 |
||
G2B=: ~:/\&.|: |
G2B=: ~:/\&.|: |
||
(,: ,.@".&.>) 'n';'#:n';'G2B inv#:n';'#.G2B G2B inv#:n' |
(,: ,.@".&.>) 'n';'#:n';'G2B inv#:n';'#.G2B G2B inv#:n' |
||
Line 2,420: | Line 2,420: | ||
|30|1 1 1 1 0|1 0 0 0 1 |30 | |
|30|1 1 1 1 0|1 0 0 0 1 |30 | |
||
|31|1 1 1 1 1|1 0 0 0 0 |31 | |
|31|1 1 1 1 1|1 0 0 0 0 |31 | |
||
+--+---------+----------+----------------+</ |
+--+---------+----------+----------------+</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="java"> |
||
public class Gray { |
public class Gray { |
||
public static long grayEncode(long n){ |
public static long grayEncode(long n){ |
||
Line 2,446: | Line 2,446: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,485: | Line 2,485: | ||
</pre> |
</pre> |
||
Here is an example encoding function that does it in a bit-by-bit, more human way: |
Here is an example encoding function that does it in a bit-by-bit, more human way: |
||
< |
<syntaxhighlight lang="java">public static long grayEncode(long n){ |
||
long result = 0; |
long result = 0; |
||
for(int exp = 0; n > 0; n /= 2, exp++){ |
for(int exp = 0; n > 0; n /= 2, exp++){ |
||
Line 2,496: | Line 2,496: | ||
} |
} |
||
return result; |
return result; |
||
}</ |
}</syntaxhighlight> |
||
This decoding function should work for gray codes of any size: |
This decoding function should work for gray codes of any size: |
||
{{untested}} |
{{untested}} |
||
< |
<syntaxhighlight lang="java">public static BigInteger grayDecode(BigInteger n){ |
||
String nBits = n.toString(2); |
String nBits = n.toString(2); |
||
String result = nBits.substring(0, 1); |
String result = nBits.substring(0, 1); |
||
Line 2,509: | Line 2,509: | ||
} |
} |
||
return new BigInteger(result, 2); |
return new BigInteger(result, 2); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Javascript}}== |
=={{header|Javascript}}== |
||
Line 2,515: | Line 2,515: | ||
'''Module''' <code>gray-code.js</code> |
'''Module''' <code>gray-code.js</code> |
||
< |
<syntaxhighlight lang="javascript">export function encode (number) { |
||
return number ^ (number >> 1) |
return number ^ (number >> 1) |
||
} |
} |
||
Line 2,527: | Line 2,527: | ||
return number |
return number |
||
}</ |
}</syntaxhighlight> |
||
'''Test''' |
'''Test''' |
||
< |
<syntaxhighlight lang="javascript">import printf from 'printf' // Module must be installed with npm first |
||
import * as gray from './gray-code.js' |
import * as gray from './gray-code.js' |
||
Line 2,550: | Line 2,550: | ||
decodedGrayCode |
decodedGrayCode |
||
)) |
)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,591: | Line 2,591: | ||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="julia">grayencode(n::Integer) = n ⊻ (n >> 1) |
||
function graydecode(n::Integer) |
function graydecode(n::Integer) |
||
r = n |
r = n |
||
Line 2,598: | Line 2,598: | ||
end |
end |
||
return r |
return r |
||
end</ |
end</syntaxhighlight> |
||
Note that these functions work for any integer type, including arbitrary-precision integers (the built-in <code>BigInt</code> type). |
Note that these functions work for any integer type, including arbitrary-precision integers (the built-in <code>BigInt</code> type). |
||
Line 2,606: | Line 2,606: | ||
Binary to Gray code |
Binary to Gray code |
||
< |
<syntaxhighlight lang="k"> xor: {~x=y} |
||
gray:{x[0],xor':x} |
gray:{x[0],xor':x} |
||
Line 2,613: | Line 2,613: | ||
/ variant: iterative |
/ variant: iterative |
||
gray2:{x[0],{:[x[y-1]=1;~x[y];x[y]]}[x]'1+!(#x)-1}</ |
gray2:{x[0],{:[x[y-1]=1;~x[y];x[y]]}[x]'1+!(#x)-1}</syntaxhighlight> |
||
Line 2,619: | Line 2,619: | ||
"Accumulated xor" |
"Accumulated xor" |
||
<lang |
<syntaxhighlight lang="k"> g2b:xor\</syntaxhighlight> |
||
An alternative is to find the inverse of the gray code by tracing until fixpoint. |
An alternative is to find the inverse of the gray code by tracing until fixpoint. |
||
Here we find that 1 1 1 1 1 is the inverse of 1 0 0 0 0 |
Here we find that 1 1 1 1 1 is the inverse of 1 0 0 0 0 |
||
< |
<syntaxhighlight lang="k"> gray\1 0 0 0 0 |
||
(1 0 0 0 0 |
(1 0 0 0 0 |
||
1 1 0 0 0 |
1 1 0 0 0 |
||
Line 2,632: | Line 2,632: | ||
1 0 1 0 1 |
1 0 1 0 1 |
||
1 1 1 1 1) |
1 1 1 1 1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
As a function (*| takes the last result) |
As a function (*| takes the last result) |
||
< |
<syntaxhighlight lang="k"> g2b1:*|{gray x}\</syntaxhighlight> |
||
Iterative version with "do" |
Iterative version with "do" |
||
< |
<syntaxhighlight lang="k"> g2b2:{c:#x;b:c#0;b[0]:x[0];i:1;do[#x;b[i]:xor[x[i];b[i-1]];i+:1];b}</syntaxhighlight> |
||
Presentation |
Presentation |
||
< |
<syntaxhighlight lang="k"> gray:{x[0],xor':x} |
||
g2b:xor\ |
g2b:xor\ |
||
/ using allcomb instead of 2_vs'!32 for nicer presentation |
/ using allcomb instead of 2_vs'!32 for nicer presentation |
||
Line 2,649: | Line 2,649: | ||
a:(+allcomb . 5 2) |
a:(+allcomb . 5 2) |
||
`0:,/{n:2_sv x;gg:gray x;gb:g2b gg;n2:2_sv gb; |
`0:,/{n:2_sv x;gg:gray x;gb:g2b gg;n2:2_sv gb; |
||
,/$((2$n)," : ",$x," -> ",$gg," -> ",$gb," : ",(2$n2),"\n") }'a</ |
,/$((2$n)," : ",$x," -> ",$gg," -> ",$gb," : ",(2$n2),"\n") }'a</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,686: | Line 2,686: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
object Gray { |
object Gray { |
||
Line 2,709: | Line 2,709: | ||
println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}") |
println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,749: | Line 2,749: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
for r =0 to 31 |
for r =0 to 31 |
||
print " Decimal "; using( "###", r); " is "; |
print " Decimal "; using( "###", r); " is "; |
||
Line 2,805: | Line 2,805: | ||
bin2Dec =t |
bin2Dec =t |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,845: | Line 2,845: | ||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="limbo">implement Gray; |
||
include "sys.m"; sys: Sys; |
include "sys.m"; sys: Sys; |
||
Line 2,894: | Line 2,894: | ||
} |
} |
||
return s; |
return s; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,934: | Line 2,934: | ||
=={{header|Lobster}}== |
=={{header|Lobster}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="lobster">def grey_encode(n) -> int: |
||
return n ^ (n >> 1) |
return n ^ (n >> 1) |
||
Line 2,952: | Line 2,952: | ||
number_to_string(g, 2, 5) + " ⇾ " + |
number_to_string(g, 2, 5) + " ⇾ " + |
||
number_to_string(b, 2, 5) + " : " + |
number_to_string(b, 2, 5) + " : " + |
||
number_to_string(b, 10, 2))</ |
number_to_string(b, 10, 2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,991: | Line 2,991: | ||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
{{trans|Euphoria}} |
{{trans|Euphoria}} |
||
< |
<syntaxhighlight lang="logo">to gray_encode :number |
||
output bitxor :number lshift :number -1 |
output bitxor :number lshift :number -1 |
||
end |
end |
||
Line 3,003: | Line 3,003: | ||
] |
] |
||
output :value |
output :value |
||
end</ |
end</syntaxhighlight> |
||
Demonstration code, including formatters: |
Demonstration code, including formatters: |
||
< |
<syntaxhighlight lang="logo">to format :str :width [pad (char 32)] |
||
while [(count :str) < :width] [ |
while [(count :str) < :width] [ |
||
make "str word :pad :str |
make "str word :pad :str |
||
Line 3,034: | Line 3,034: | ||
print (sentence (format :num 2) ": (binary :num 5) ": (binary :gray 5) ": |
print (sentence (format :num 2) ": (binary :num 5) ": (binary :gray 5) ": |
||
(binary :decoded 5) ": (format :decoded 2)) ] |
(binary :decoded 5) ": (format :decoded 2)) ] |
||
bye</ |
bye</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,074: | Line 3,074: | ||
{{trans|Euphoria}} |
{{trans|Euphoria}} |
||
This code uses the [http://bitop.luajit.org/index.html Lua BitOp] module. Designed to be a module named <tt>gray.lua</tt>. |
This code uses the [http://bitop.luajit.org/index.html Lua BitOp] module. Designed to be a module named <tt>gray.lua</tt>. |
||
< |
<syntaxhighlight lang="lua">local _M = {} |
||
local bit = require('bit') |
local bit = require('bit') |
||
Line 3,091: | Line 3,091: | ||
end |
end |
||
return _M</ |
return _M</syntaxhighlight> |
||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="lua">local bit = require 'bit' |
||
local gray = require 'gray' |
local gray = require 'gray' |
||
Line 3,117: | Line 3,117: | ||
to_bit_string(i,5), to_bit_string(g, 5), |
to_bit_string(i,5), to_bit_string(g, 5), |
||
to_bit_string(gd,5), gd)) |
to_bit_string(gd,5), gd)) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,161: | Line 3,161: | ||
Additions to showing the modules/functions replacement mechanism of M2000 |
Additions to showing the modules/functions replacement mechanism of M2000 |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Code32 (&code(), &decode()){ |
Module Code32 (&code(), &decode()){ |
||
Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}" |
Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}" |
||
Line 3,191: | Line 3,191: | ||
// pass Code32 to GrayCode in place of doit |
// pass Code32 to GrayCode in place of doit |
||
GrayCode ; doit as Code32 |
GrayCode ; doit as Code32 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;"> |
<pre style="overflow: auto; height: 20em;"> |
||
Line 3,230: | Line 3,230: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">graycode[n_]:=BitXor[n,BitShiftRight[n]] |
||
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]</ |
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Required example: |
<pre>Required example: |
||
Line 3,247: | Line 3,247: | ||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
<syntaxhighlight lang="matlab"> |
|||
<lang MATLAB> |
|||
%% Gray Code Generator |
%% Gray Code Generator |
||
% this script generates gray codes of n bits |
% this script generates gray codes of n bits |
||
Line 3,291: | Line 3,291: | ||
disp(result); |
disp(result); |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,344: | Line 3,344: | ||
The additional <tt>gray.coerce/2</tt> predicate converts the ''representation'' underlying a <tt>gray</tt> value into an <tt>int</tt> value or vice versa (it is moded in both directions). For type safety reasons we do not wish to generally expose the underlying representation, but for some purposes, most notably I/O or storage or their ilk we have to break the type safety. The <tt>coerce/2</tt> predicate is used for this purpose. |
The additional <tt>gray.coerce/2</tt> predicate converts the ''representation'' underlying a <tt>gray</tt> value into an <tt>int</tt> value or vice versa (it is moded in both directions). For type safety reasons we do not wish to generally expose the underlying representation, but for some purposes, most notably I/O or storage or their ilk we have to break the type safety. The <tt>coerce/2</tt> predicate is used for this purpose. |
||
< |
<syntaxhighlight lang="mercury">:- module gray. |
||
:- interface. |
:- interface. |
||
Line 3,373: | Line 3,373: | ||
gray.coerce(gray(I), I). |
gray.coerce(gray(I), I). |
||
:- end_module gray.</ |
:- end_module gray.</syntaxhighlight> |
||
The following program tests the above code: |
The following program tests the above code: |
||
< |
<syntaxhighlight lang="mercury">:- module gray_test. |
||
:- interface. |
:- interface. |
||
Line 3,416: | Line 3,416: | ||
io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO). |
io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO). |
||
:- end_module gray_test.</ |
:- end_module gray_test.</syntaxhighlight> |
||
The <tt>main/2</tt> predicate generates a list of numbers from 0 to 31 inclusive and then checks that conversion is working properly. |
The <tt>main/2</tt> predicate generates a list of numbers from 0 to 31 inclusive and then checks that conversion is working properly. |
||
Line 3,476: | Line 3,476: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="nim">proc grayEncode(n: int): int = |
||
n xor (n shr 1) |
n xor (n shr 1) |
||
Line 3,484: | Line 3,484: | ||
while t > 0: |
while t > 0: |
||
t = t shr 1 |
t = t shr 1 |
||
result = result xor t</ |
result = result xor t</syntaxhighlight> |
||
Demonstration code: |
Demonstration code: |
||
< |
<syntaxhighlight lang="nim">import strutils, strformat |
||
for i in 0 .. 32: |
for i in 0 .. 32: |
||
echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"</ |
echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 0 => 000000 => 0 |
<pre> 0 => 000000 => 0 |
||
Line 3,527: | Line 3,527: | ||
=={{header|NOWUT}}== |
=={{header|NOWUT}}== |
||
adapted from C |
adapted from C |
||
< |
<syntaxhighlight lang="nowut">; link with PIOxxx.OBJ |
||
sectiondata |
sectiondata |
||
Line 3,591: | Line 3,591: | ||
endfunc |
endfunc |
||
returnex $0C ; clean off 3 parameters from the stack |
returnex $0C ; clean off 3 parameters from the stack |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">00 : 00000 => 00000 => 00000 |
<pre style="overflow: auto; height: 20em;">00 : 00000 => 00000 => 00000 |
||
Line 3,628: | Line 3,628: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let gray_encode b = |
||
b lxor (b lsr 1) |
b lxor (b lsr 1) |
||
Line 3,653: | Line 3,653: | ||
let b = gray_decode g in |
let b = gray_decode g in |
||
Printf.printf "%2d : %s => %s => %s : %2d\n" i (s i) (s g) (s b) b |
Printf.printf "%2d : %s => %s => %s : %2d\n" i (s i) (s g) (s b) b |
||
done</ |
done</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
This code may have exposed a bug in PARI 2.4.4: <code>apply(Str, 1)</code> fails. |
This code may have exposed a bug in PARI 2.4.4: <code>apply(Str, 1)</code> fails. |
||
As a workaround I used a closure: <code>apply(k->Str(k), 1)</code>. |
As a workaround I used a closure: <code>apply(k->Str(k), 1)</code>. |
||
< |
<syntaxhighlight lang="parigp">toGray(n)=bitxor(n,n>>1); |
||
fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n; |
fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n; |
||
bin(n)=concat(apply(k->Str(k),binary(n))) |
bin(n)=concat(apply(k->Str(k),binary(n))) |
||
for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))</ |
for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 0 0 0 |
<pre>0 0 0 0 |
||
Line 3,702: | Line 3,702: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub bin2gray |
||
{ |
{ |
||
return $_[0] ^ ($_[0] >> 1); |
return $_[0] ^ ($_[0] >> 1); |
||
Line 3,721: | Line 3,721: | ||
my $gr= bin2gray($_); |
my $gr= bin2gray($_); |
||
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr); |
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{Trans|Delphi}} (turned out to be almost the same as Euphoria) |
{{Trans|Delphi}} (turned out to be almost the same as Euphoria) |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">gray_encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">gray_encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
||
Line 3,748: | Line 3,748: | ||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d %05b %05b %2d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d %05b %05b %2d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,788: | Line 3,788: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"> |
||
<?php |
<?php |
||
Line 3,817: | Line 3,817: | ||
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); |
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,855: | Line 3,855: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
foreach(I in 0..2**5-1) |
foreach(I in 0..2**5-1) |
||
G = gray_encode1(I), |
G = gray_encode1(I), |
||
Line 3,880: | Line 3,880: | ||
P := P ^ N, |
P := P ^ N, |
||
N := N >> 1 |
N := N >> 1 |
||
end. </ |
end. </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,920: | Line 3,920: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de grayEncode (N) |
||
(bin (x| N (>> 1 N))) ) |
(bin (x| N (>> 1 N))) ) |
||
Line 3,929: | Line 3,929: | ||
(mapcar |
(mapcar |
||
'((C) (setq X (x| X (format C)))) |
'((C) (setq X (x| X (format C)))) |
||
(chop G) ) ) ) ) )</ |
(chop G) ) ) ) ) )</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="picolisp">(prinl " Binary Gray Decoded") |
||
(for I (range 0 31) |
(for I (range 0 31) |
||
(let G (grayEncode I) |
(let G (grayEncode I) |
||
(tab (4 9 9 9) I (bin I) G (grayDecode G)) ) )</ |
(tab (4 9 9 9) I (bin I) G (grayDecode G)) ) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> Binary Gray Decoded |
<pre> Binary Gray Decoded |
||
Line 3,971: | Line 3,971: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">(stringrange, stringsize): |
||
Gray_code: procedure options (main); /* 15 November 2013 */ |
Gray_code: procedure options (main); /* 15 November 2013 */ |
||
declare (bin(0:31), g(0:31), b2(0:31)) bit (5); |
declare (bin(0:31), g(0:31), b2(0:31)) bit (5); |
||
Line 4,001: | Line 4,001: | ||
put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b)); |
put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b)); |
||
end; |
end; |
||
end Gray_code;</ |
end Gray_code;</syntaxhighlight> |
||
<pre> |
<pre> |
||
0 00000 00000 00000 |
0 00000 00000 00000 |
||
Line 4,038: | Line 4,038: | ||
=={{header|PowerBASIC}}== |
=={{header|PowerBASIC}}== |
||
< |
<syntaxhighlight lang="powerbasic">function gray%(byval n%) |
||
gray%=n% xor (n%\2) |
gray%=n% xor (n%\2) |
||
end function |
end function |
||
Line 4,055: | Line 4,055: | ||
g%=gray%(n%) |
g%=gray%(n%) |
||
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%)) |
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%)) |
||
next</ |
next</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 4,065: | Line 4,065: | ||
{{works with|SWI Prolog}} |
{{works with|SWI Prolog}} |
||
{{works with|YAP}} |
{{works with|YAP}} |
||
< |
<syntaxhighlight lang="prolog">to_gray(N, G) :- |
||
N0 is N >> 1, |
N0 is N >> 1, |
||
G is N xor N0. |
G is N xor N0. |
||
Line 4,074: | Line 4,074: | ||
from_gray(S, N0), |
from_gray(S, N0), |
||
N is G xor N0 |
N is G xor N0 |
||
; N is G ).</ |
; N is G ).</syntaxhighlight> |
||
=== Test Code === |
=== Test Code === |
||
Line 4,082: | Line 4,082: | ||
{{works with|SWI Prolog}} |
{{works with|SWI Prolog}} |
||
{{works with|YAP}} |
{{works with|YAP}} |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(apply)). |
||
to_gray(N, G) :- |
to_gray(N, G) :- |
||
Line 4,113: | Line 4,113: | ||
maplist(write_record, Numbers, Grays, Decodeds). |
maplist(write_record, Numbers, Grays, Decodeds). |
||
go :- halt(1). |
go :- halt(1). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 4,155: | Line 4,155: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure.i gray_encode(n) |
||
ProcedureReturn n ! (n >> 1) |
ProcedureReturn n ! (n >> 1) |
||
EndProcedure |
EndProcedure |
||
Line 4,185: | Line 4,185: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Number Gray Binary Decoded |
<pre>Number Gray Binary Decoded |
||
Line 4,225: | Line 4,225: | ||
===Python: on integers=== |
===Python: on integers=== |
||
Works with python integers |
Works with python integers |
||
<lang>def gray_encode(n): |
<syntaxhighlight lang="text">def gray_encode(n): |
||
return n ^ n >> 1 |
return n ^ n >> 1 |
||
Line 4,241: | Line 4,241: | ||
gray = gray_encode(i) |
gray = gray_encode(i) |
||
dec = gray_decode(gray) |
dec = gray_decode(gray) |
||
print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}")</ |
print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,283: | Line 4,283: | ||
;First some int<>bin conversion routines: |
;First some int<>bin conversion routines: |
||
< |
<syntaxhighlight lang="python">>>> def int2bin(n): |
||
'From positive integer to list of binary bits, msb at index 0' |
'From positive integer to list of binary bits, msb at index 0' |
||
if n: |
if n: |
||
Line 4,299: | Line 4,299: | ||
for bit in bits: |
for bit in bits: |
||
i = i * 2 + bit |
i = i * 2 + bit |
||
return i</ |
return i</syntaxhighlight> |
||
;Now the bin<>gray converters. |
;Now the bin<>gray converters. |
||
These follow closely the methods in the animation seen here: [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes]. |
These follow closely the methods in the animation seen here: [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes]. |
||
< |
<syntaxhighlight lang="python">>>> def bin2gray(bits): |
||
return bits[:1] + [i ^ ishift for i, ishift in zip(bits[:-1], bits[1:])] |
return bits[:1] + [i ^ ishift for i, ishift in zip(bits[:-1], bits[1:])] |
||
Line 4,309: | Line 4,309: | ||
b = [bits[0]] |
b = [bits[0]] |
||
for nextb in bits[1:]: b.append(b[-1] ^ nextb) |
for nextb in bits[1:]: b.append(b[-1] ^ nextb) |
||
return b</ |
return b</syntaxhighlight> |
||
;Sample output |
;Sample output |
||
< |
<syntaxhighlight lang="python">>>> for i in range(16): |
||
print('int:%2i -> bin:%12r -> gray:%12r -> bin:%12r -> int:%2i' % |
print('int:%2i -> bin:%12r -> gray:%12r -> bin:%12r -> int:%2i' % |
||
( i, |
( i, |
||
Line 4,338: | Line 4,338: | ||
int:14 -> bin:[1, 1, 1, 0] -> gray:[1, 0, 0, 1] -> bin:[1, 1, 1, 0] -> int:14 |
int:14 -> bin:[1, 1, 1, 0] -> gray:[1, 0, 0, 1] -> bin:[1, 1, 1, 0] -> int:14 |
||
int:15 -> bin:[1, 1, 1, 1] -> gray:[1, 0, 0, 0] -> bin:[1, 1, 1, 1] -> int:15 |
int:15 -> bin:[1, 1, 1, 1] -> gray:[1, 0, 0, 0] -> bin:[1, 1, 1, 1] -> int:15 |
||
>>> </ |
>>> </syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ dup 1 >> ^ ] is encodegray ( n --> n ) |
||
[ dup |
[ dup |
||
Line 4,363: | Line 4,363: | ||
i^ encodegray dup 5 echobin |
i^ encodegray dup 5 echobin |
||
say " -> " |
say " -> " |
||
decodegray 5 echobin cr ]</ |
decodegray 5 echobin cr ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,403: | Line 4,403: | ||
=={{header|R}}== |
=={{header|R}}== |
||
<syntaxhighlight lang="r"> |
|||
<lang r> |
|||
GrayEncode <- function(binary) { |
GrayEncode <- function(binary) { |
||
gray <- substr(binary,1,1) |
gray <- substr(binary,1,1) |
||
Line 4,429: | Line 4,429: | ||
return (binary) |
return (binary) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 4,451: | Line 4,451: | ||
(~a (to-bin(gray-encode i)) #:width 5 #:align 'right #:pad-string "0") |
(~a (to-bin(gray-encode i)) #:width 5 #:align 'right #:pad-string "0") |
||
(~a (to-bin (gray-decode(gray-encode i))) #:width 5 #:align 'right #:pad-string "0")))) |
(~a (to-bin (gray-decode(gray-encode i))) #:width 5 #:align 'right #:pad-string "0")))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">> (show-table) |
<pre style="overflow: auto; height: 20em;">> (show-table) |
||
Line 4,489: | Line 4,489: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<syntaxhighlight lang="raku" line> |
|||
<lang perl6> |
|||
sub gray_encode ( Int $n --> Int ) { |
sub gray_encode ( Int $n --> Int ) { |
||
return $n +^ ( $n +> 1 ); |
return $n +^ ( $n +> 1 ); |
||
Line 4,506: | Line 4,506: | ||
die if $d != $n; |
die if $d != $n; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 4,549: | Line 4,549: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
The leading zeroes for the binary numbers and the gray code could've easily been elided. |
The leading zeroes for the binary numbers and the gray code could've easily been elided. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program converts decimal number ───► binary ───► gray code ───► binary.*/ |
||
parse arg N . /*get the optional argument from the CL*/ |
parse arg N . /*get the optional argument from the CL*/ |
||
if N=='' | N=="," then N=31 /*Not specified? Then use the default.*/ |
if N=='' | N=="," then N=31 /*Not specified? Then use the default.*/ |
||
Line 4,573: | Line 4,573: | ||
end /*g*/ /* ↑ */ |
end /*g*/ /* ↑ */ |
||
/* │ */ |
/* │ */ |
||
return $ /*this is an eXclusive OR ►─────────┘ */</ |
return $ /*this is an eXclusive OR ►─────────┘ */</syntaxhighlight> |
||
'''output''' when using the default input: |
'''output''' when using the default input: |
||
<pre> |
<pre> |
||
Line 4,612: | Line 4,612: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Gray code |
# Project : Gray code |
||
Line 4,649: | Line 4,649: | ||
result = result + string(binary) |
result = result + string(binary) |
||
return result |
return result |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,689: | Line 4,689: | ||
<tt>Integer#from_gray</tt> has recursion so it can use each bit of the answer to compute the next bit. |
<tt>Integer#from_gray</tt> has recursion so it can use each bit of the answer to compute the next bit. |
||
< |
<syntaxhighlight lang="ruby">class Integer |
||
# Converts a normal integer to a Gray code. |
# Converts a normal integer to a Gray code. |
||
def to_gray |
def to_gray |
||
Line 4,713: | Line 4,713: | ||
printf "%2d : %5b => %5b => %5b : %2d\n", |
printf "%2d : %5b => %5b => %5b : %2d\n", |
||
number, number, encoded, decoded, decoded |
number, number, encoded, decoded, decoded |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;"> |
<pre style="overflow: auto; height: 20em;"> |
||
Line 4,752: | Line 4,752: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{works with|Rust|1.1}} |
{{works with|Rust|1.1}} |
||
< |
<syntaxhighlight lang="rust">fn gray_encode(integer: u64) -> u64 { |
||
(integer >> 1) ^ integer |
(integer >> 1) ^ integer |
||
} |
} |
||
Line 4,769: | Line 4,769: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 4,775: | Line 4,775: | ||
The <code>scanLeft</code> function takes a sequence (here, of characters) and produces a collection containing cumulative results of applying an operator going left to right. |
The <code>scanLeft</code> function takes a sequence (here, of characters) and produces a collection containing cumulative results of applying an operator going left to right. |
||
Here the operator is exclusive-or, "^", and we can use "_" placeholders to represent the arguments to the left and right. <code>tail</code> removes the "0" we added as the initial accumulator value, and <code>mkString</code> turns the collection back into a String, that we can parse into an integer (Integer.parseInt is directly from the java.lang package). |
Here the operator is exclusive-or, "^", and we can use "_" placeholders to represent the arguments to the left and right. <code>tail</code> removes the "0" we added as the initial accumulator value, and <code>mkString</code> turns the collection back into a String, that we can parse into an integer (Integer.parseInt is directly from the java.lang package). |
||
< |
<syntaxhighlight lang="scala">def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString |
||
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2) |
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2) |
||
Line 4,781: | Line 4,781: | ||
for (i <- 0 to 31; g = encode(i)) |
for (i <- 0 to 31; g = encode(i)) |
||
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g))) |
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded |
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded |
||
Line 4,818: | Line 4,818: | ||
</pre> |
</pre> |
||
Alternatively, more imperative style: |
Alternatively, more imperative style: |
||
< |
<syntaxhighlight lang="scala">def encode(n: Long) = n ^ (n >>> 1) |
||
def decode(n: Long) = { |
def decode(n: Long) = { |
||
Line 4,836: | Line 4,836: | ||
val g = encode(i) |
val g = encode(i) |
||
println("%7d %6s %5s %7s".format(i, toBin(i), toBin(g), decode(g))) |
println("%7d %6s %5s %7s".format(i, toBin(i), toBin(g), decode(g))) |
||
}</ |
}</syntaxhighlight> |
||
Improved version of decode using functional style (recursion+local method). |
Improved version of decode using functional style (recursion+local method). |
||
No vars and mutations. |
No vars and mutations. |
||
< |
<syntaxhighlight lang="scala">def decode(n:Long)={ |
||
def calc(g:Long,bits:Long):Long=if (bits>0) calc(g^bits, bits>>1) else g |
def calc(g:Long,bits:Long):Long=if (bits>0) calc(g^bits, bits>>1) else g |
||
calc(0, n) |
calc(0, n) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded |
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded |
||
Line 4,887: | Line 4,887: | ||
The type [http://seed7.sourceforge.net/libraries/bin32.htm bin32] is intended for bit operations that are not defined for [http://seed7.sourceforge.net/libraries/integer.htm integer] values. |
The type [http://seed7.sourceforge.net/libraries/bin32.htm bin32] is intended for bit operations that are not defined for [http://seed7.sourceforge.net/libraries/integer.htm integer] values. |
||
Bin32 is used for the [http://seed7.sourceforge.net/libraries/bin32.htm#%28in_bin32%29%3E%3C%28in_bin32%29 exclusive or] ('''><''') operation. |
Bin32 is used for the [http://seed7.sourceforge.net/libraries/bin32.htm#%28in_bin32%29%3E%3C%28in_bin32%29 exclusive or] ('''><''') operation. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "bin32.s7i"; |
include "bin32.s7i"; |
||
Line 4,911: | Line 4,911: | ||
writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i))); |
writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i))); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,952: | Line 4,952: | ||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
Note: Inputs and outputs as strings |
Note: Inputs and outputs as strings |
||
< |
<syntaxhighlight lang="sensetalk"> |
||
function BinaryToGray param1 |
function BinaryToGray param1 |
||
set theResult to "" |
set theResult to "" |
||
Line 4,990: | Line 4,990: | ||
return theResult |
return theResult |
||
end GrayToBinary |
end GrayToBinary |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 5,034: | Line 5,034: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">func bin2gray(n) { |
||
n ^ (n >> 1) |
n ^ (n >> 1) |
||
} |
} |
||
Line 5,047: | Line 5,047: | ||
var gr = bin2gray(i) |
var gr = bin2gray(i) |
||
printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr)) |
printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr)) |
||
} << ^32</ |
} << ^32</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,085: | Line 5,085: | ||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
< |
<syntaxhighlight lang="sql"> |
||
DECLARE @binary AS NVARCHAR(MAX) = '001010111' |
DECLARE @binary AS NVARCHAR(MAX) = '001010111' |
||
DECLARE @gray AS NVARCHAR(MAX) = '' |
DECLARE @gray AS NVARCHAR(MAX) = '' |
||
Line 5,118: | Line 5,118: | ||
SELECT @binary |
SELECT @binary |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">fun gray_encode b = |
||
Word.xorb (b, Word.>> (b, 0w1)) |
Word.xorb (b, Word.>> (b, 0w1)) |
||
Line 5,146: | Line 5,146: | ||
aux (i + 0w1) |
aux (i + 0w1) |
||
end; |
end; |
||
aux 0w0</ |
aux 0w0</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func grayEncode(_ i: Int) -> Int { |
||
return (i >> 1) ^ i |
return (i >> 1) ^ i |
||
} |
} |
||
Line 5,171: | Line 5,171: | ||
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))") |
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,209: | Line 5,209: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">namespace eval gray { |
||
proc encode n { |
proc encode n { |
||
expr {$n ^ $n >> 1} |
expr {$n ^ $n >> 1} |
||
Line 5,222: | Line 5,222: | ||
return $b |
return $b |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating: |
Demonstrating: |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.6; # Just for %b format specifier |
||
for {set i 0} {$i < 32} {incr i} { |
for {set i 0} {$i < 32} {incr i} { |
||
set g [gray::encode $i] |
set g [gray::encode $i] |
||
set b [gray::decode $g] |
set b [gray::decode $g] |
||
puts [format "%2d: %05b => %05b => %05b : %2d" $i $i $g $b $b] |
puts [format "%2d: %05b => %05b => %05b : %2d" $i $i $g $b $b] |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,268: | Line 5,268: | ||
== {{header|TypeScript}} == |
== {{header|TypeScript}} == |
||
{{trans|DWScript}} |
{{trans|DWScript}} |
||
< |
<syntaxhighlight lang="javascript">// Gray code |
||
function encode(v: number): number { |
function encode(v: number): number { |
||
Line 5,295: | Line 5,295: | ||
console.log(); |
console.log(); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,335: | Line 5,335: | ||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
Line 5,346: | Line 5,346: | ||
#show+ |
#show+ |
||
test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,btog,gtob+ btog>* iota32</ |
test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,btog,gtob+ btog>* iota32</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,385: | Line 5,385: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Function Encoder(ByVal n) |
||
Encoder = n Xor (n \ 2) |
Encoder = n Xor (n \ 2) |
||
End Function |
End Function |
||
Line 5,413: | Line 5,413: | ||
decoded = Decoder(encoded) |
decoded = Decoder(encoded) |
||
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) |
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) |
||
Next</ |
Next</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary |
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary |
||
Line 5,453: | Line 5,453: | ||
'''Function Based Approach:''' |
'''Function Based Approach:''' |
||
<syntaxhighlight lang="verilog"> |
|||
<lang Verilog> |
|||
`timescale 1ns/10ps |
`timescale 1ns/10ps |
||
`default_nettype wire |
`default_nettype wire |
||
Line 5,500: | Line 5,500: | ||
`default_nettype none |
`default_nettype none |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Module Based Approach:''' |
'''Module Based Approach:''' |
||
<syntaxhighlight lang="verilog"> |
|||
<lang Verilog> |
|||
`timescale 1ns/10ps |
`timescale 1ns/10ps |
||
`default_nettype none |
`default_nettype none |
||
Line 5,549: | Line 5,549: | ||
`default_nettype none |
`default_nettype none |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VHDL}}== |
=={{header|VHDL}}== |
||
Combinatorial encoder: |
Combinatorial encoder: |
||
< |
<syntaxhighlight lang="vhdl">LIBRARY ieee; |
||
USE ieee.std_logic_1164.all; |
USE ieee.std_logic_1164.all; |
||
Line 5,566: | Line 5,566: | ||
begin |
begin |
||
gray <= bin(n) & ( bin(N-1 downto 0) xor bin(N downto 1)); |
gray <= bin(n) & ( bin(N-1 downto 0) xor bin(N downto 1)); |
||
end architecture rtl;</ |
end architecture rtl;</syntaxhighlight> |
||
Combinatorial decoder: |
Combinatorial decoder: |
||
< |
<syntaxhighlight lang="vhdl">LIBRARY ieee; |
||
USE ieee.std_logic_1164.all; |
USE ieee.std_logic_1164.all; |
||
Line 5,585: | Line 5,585: | ||
bin(i) <= gray(i) xor bin(i+1); |
bin(i) <= gray(i) xor bin(i+1); |
||
end generate; |
end generate; |
||
end architecture rtl;</ |
end architecture rtl;</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read. |
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read. |
||
< |
<syntaxhighlight lang="go">fn enc(b int) int { |
||
return b ^ b>>1 |
return b ^ b>>1 |
||
} |
} |
||
Line 5,610: | Line 5,610: | ||
println(" ${b:2} ${b:05b} ${g:05b} ${d:05b} ${d:2}") |
println(" ${b:2} ${b:05b} ${g:05b} ${d:05b} ${d:2}") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as Go.</pre> |
<pre>Same as Go.</pre> |
||
Line 5,616: | Line 5,616: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
var toGray = Fn.new { |n| n ^ (n>>1) } |
var toGray = Fn.new { |n| n ^ (n>>1) } |
||
Line 5,635: | Line 5,635: | ||
System.write(" %(Fmt.bz(5, g))") |
System.write(" %(Fmt.bz(5, g))") |
||
System.print(" %(Fmt.bz(5, fromGray.call(g)))") |
System.print(" %(Fmt.bz(5, fromGray.call(g)))") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,678: | Line 5,678: | ||
Intrinsic function <code>BIN$</code> has been used. |
Intrinsic function <code>BIN$</code> has been used. |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
< |
<syntaxhighlight lang="xbasic">' Gray code |
||
PROGRAM "graycode" |
PROGRAM "graycode" |
||
VERSION "0.0001" |
VERSION "0.0001" |
||
Line 5,708: | Line 5,708: | ||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,747: | Line 5,747: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
func Gray2Bin(N); \Convert N from Gray code to binary |
func Gray2Bin(N); \Convert N from Gray code to binary |
||
Line 5,782: | Line 5,782: | ||
BinOut(Gray2Bin(G)); CrLf(0); |
BinOut(Gray2Bin(G)); CrLf(0); |
||
]; |
]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,821: | Line 5,821: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn grayEncode(n){ n.bitXor(n.shiftRight(1)) } |
||
fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b }</ |
fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b }</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">foreach n in ([0..31]){ |
||
g:=grayEncode(n); b:=grayDecode(g); |
g:=grayEncode(n); b:=grayDecode(g); |
||
println("%2d(%05.2B) --> %2d(%05.2B) --> %2d(%05.2B)".fmt(n,n,g,g,b,b)); |
println("%2d(%05.2B) --> %2d(%05.2B) --> %2d(%05.2B)".fmt(n,n,g,g,b,b)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="overflow: auto; height: 20em;"> |
<pre style="overflow: auto; height: 20em;"> |