Skip to content

Instantly share code, notes, and snippets.

@danielevans
Created July 8, 2012 05:31
Show Gist options
  • Select an option

  • Save danielevans/3069540 to your computer and use it in GitHub Desktop.

Select an option

Save danielevans/3069540 to your computer and use it in GitHub Desktop.
String decoder in Ruby
# 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') == []
@clintberry
Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment