Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active November 12, 2015 23:13
Show Gist options
  • Save tuscen/e81a7028bf149a83b46a to your computer and use it in GitHub Desktop.
Save tuscen/e81a7028bf149a83b46a to your computer and use it in GitHub Desktop.
class Gray_code
def self.encode number
( number ^ ( number >> 1 ) ).to_s(2)
end
def self.decode number
bin = number[0]
(number.length-1).times do |i|
bin += ( number[i+1].to_i(2) ^ bin[i].to_i(2) ).to_s(2)
end
bin
end
end
p Gray_code::encode 125125
p Gray_code::decode((Gray_code::encode 125125)).to_i(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment