ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

cjavdev's solution

to Secret Handshake in the Ruby Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

There are 10 types of people in the world: Those who understand binary, and those who don't.

You and your fellow cohort of those in the "know" when it comes to binary decide to come up with a secret "handshake".

``````1 = wink
1000 = jump

10000 = Reverse the order of the operations in the secret handshake.
``````

Given a decimal number, convert it to the appropriate sequence of events for a secret handshake.

Here's a couple of examples:

Given the input 3, the function would return the array ["wink", "double blink"] because 3 is 11 in binary.

Given the input 19, the function would return the array ["double blink", "wink"] because 19 is 10011 in binary. Notice that the addition of 16 (10000 in binary) has caused the array to be reversed.

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

``````gem install minitest
``````

If you would like color output, you can `require 'minitest/pride'` in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

``````ruby secret_handshake_test.rb
``````

To include color from the command line:

``````ruby -r minitest/pride secret_handshake_test.rb
``````

Source

Bert, in Mary Poppins http://www.imdb.com/title/tt0058331/quotes/qt0437047

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

secret_handshake_test.rb

``````require 'minitest/autorun'
require_relative 'secret_handshake'

class SecretHandshakeTest < Minitest::Test
def test_handshake_1_to_wink
handshake = SecretHandshake.new(1)
assert_equal ['wink'], handshake.commands
end

skip
handshake = SecretHandshake.new(2)
end

def test_handshake_100_to_close_your_eyes
skip
handshake = SecretHandshake.new(4)
end

def test_handshake_1000_to_jump
skip
handshake = SecretHandshake.new(8)
assert_equal ['jump'], handshake.commands
end

skip
handshake = SecretHandshake.new(3)
end

skip
handshake = SecretHandshake.new(19)
end

skip
handshake = SecretHandshake.new(31)
assert_equal expected, handshake.commands
end

def test_invalid_handshake
skip
handshake = SecretHandshake.new('piggies')
assert_equal [], handshake.commands
end
end``````
``````class SecretHandshake
COMMANDS = [
'wink',
'jump'
].freeze

def initialize(input)
@signal = input.to_i
@bits = signal
.to_s(2)
.chars
.reverse
.map(&:to_i)
end

def commands
commands = bits
.zip(COMMANDS)
.select { |el| el[0].nonzero? }
.map(&:last)
.compact
signal >= 16 ? commands.reverse : commands
end

private

end``````