Last active
September 24, 2016 16:27
-
-
Save nerboda/1976a77a38a1232e08bd085f1bb72d96 to your computer and use it in GitHub Desktop.
Weekly Challenge - Secret Handshake
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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