Skip to content

Instantly share code, notes, and snippets.

@rpepato
Created March 9, 2013 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpepato/5124032 to your computer and use it in GitHub Desktop.
Save rpepato/5124032 to your computer and use it in GitHub Desktop.
Algorithm to calculate the gray code for a specified number of bits, using recursion in ruby
def gray_code_for(number_of_bits)
if number_of_bits == 1
return %w[0 1]
end
ordered = gray_code_for(number_of_bits - 1)
reversed = ordered.reverse
ordered.map! { |item| "0#{item}"}
reversed.map! { |item| "1#{item}"}
ordered + reversed
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment