Skip to content

Instantly share code, notes, and snippets.

@nerboda
Last active September 24, 2016 16:27
Show Gist options
  • Save nerboda/1976a77a38a1232e08bd085f1bb72d96 to your computer and use it in GitHub Desktop.
Save nerboda/1976a77a38a1232e08bd085f1bb72d96 to your computer and use it in GitHub Desktop.
Weekly Challenge - Secret Handshake
# A SecretHandshake class that decodes binary commands in a secret language
class SecretHandshake
SECRETS = ['wink', 'double blink', 'close your eyes', 'jump'].freeze
def initialize(num)
@bits = to_binary(num).chars.reverse
end
def commands
secrets = @bits.map.with_index { |bit, idx| SECRETS[idx] if bit == '1' }
secrets.reverse! if @bits[4] == '1'
secrets.compact
end
private
def to_binary(num)
return '0' if num =~ /[a-zA-Z]/
indexes = ones_indexes(num)
string = '0' * (Math.log2(num).to_i + 1)
indexes.each { |digit| string[digit] = '1' }
string
end
def ones_indexes(num)
array = []
while num > 0
power = Math.log2(num).to_i
array << -power - 1
num = num.zero? ? num - 1 : num - (2**power)
end
array
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment