Created
July 8, 2012 05:31
-
-
Save danielevans/3069540 to your computer and use it in GitHub Desktop.
String decoder in Ruby
This file contains hidden or 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
| # build a hash that links number to char, so { "1" => "a", "2" => "b", ... } | |
| CODES = (0..25).reduce Hash.new do |memo, code| | |
| memo[(code + 1).to_s] = (code + 'a'.ord).chr | |
| memo | |
| end | |
| # recursive method | |
| def decode(str) | |
| # terminal case if the string given is empty | |
| return [] if str.empty? | |
| results = [] | |
| # loop over each pair and see if the string begins with each char code | |
| CODES.each_pair do |key, value| | |
| if str.start_with?(key) && !str.start_with?(key + "0") | |
| # get a new string without the leading keycode | |
| new_str = str.gsub(/^#{key}/, '') | |
| if new_str.empty? | |
| # if the new string is empty, this is a valid solution | |
| results << value | |
| else | |
| # otherwise, decode the new string and each one of those is a correct solution | |
| decode(new_str).each do |possability| | |
| results << (value + possability) | |
| end | |
| end | |
| end | |
| end | |
| results | |
| end | |
| # tdd ftw | |
| raise "wrong" unless decode('105') == ["je"] | |
| raise "wrong" unless decode('2175') == ['bage', 'bqe', 'uge'] | |
| raise "wrong" unless decode('2222') == ['bbbb','bbv','bvb','vbb','vv'] | |
| raise "wrong" unless decode('0000') == [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And in python: https://gist.github.com/3379979
:-)