Function Repository Resource:

GrayCode

Source Notebook

Find the Gray code for an integer

Contributed by: Wolfram Staff

ResourceFunction["GrayCode"][n]

gives the Gray code of the integer n.

Examples

Basic Examples (2) 

Find the Gray code of an integer:

In[1]:=
ResourceFunction["GrayCode"][14]
Out[1]=

GrayCode threads itself elementwise over lists:

In[2]:=
ResourceFunction["GrayCode"][Range[25]]
Out[2]=

Applications (1) 

Visualize the sequence of values generated by GrayCode:

In[3]:=
ListLinePlot[
 Table[FromDigits[ResourceFunction["GrayCode"][n], 2], {n, 100}]]
Out[3]=

Properties and Relations (2) 

Successive values differ in only one bit in the binary representation:

In[4]:=
gc = PadLeft[ResourceFunction["GrayCode"][Range[15]], {15, 4}]
Out[4]=
In[5]:=
diff = Differences[gc]
Out[5]=

Visualize the differences:

In[6]:=
ArrayPlot[diff, ColorFunction -> "TemperatureMap"]
Out[6]=

Neat Examples (1) 

Create an animated fractal from the sequence generated by GrayCode:

In[7]:=
ResourceFunction[
ResourceObject[
Association[
   "Name" -> "SimpleListAnimate", "ShortName" -> "SimpleListAnimate", "UUID" -> "fa4f1a81-dd00-480d-b3d3-edf987ea2c04", "ResourceType" -> "Function", "Version" -> "1.0.0", "Description" -> "Create an animation from a list of expressions",
     "RepositoryLocation" -> URL[
     "https://www.wolframcloud.com/objects/resourcesystem/api/1.0"], "SymbolName" -> "FunctionRepository`$\
e2dce3b063014c54a0f928097aae3b4a`SimpleListAnimate"], ResourceSystemBase -> Automatic]][
 Table[ListLinePlot[
   Table[FromDigits[ResourceFunction["GrayCode"][n], 2], {n, 2^m - 1}], Axes -> False], {m, 10}]]
Out[7]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 2.0.1 – 28 June 2021
  • 2.0.0 – 03 February 2020
  • 1.0.0 – 15 August 2018

Related Resources

License Information