Reputation: 33
I'm trying to solve a code challenge about Morse Code, the idea is to:
morse_text = '.... ..|--. ..- -.-- ...'
'HI GUYS'
'HIGUYS'
where the pipe should be converted into a space between the 2 words. So far I got:
def decode(morse_text)
# TODO: Decode the morse text
morse_text = morse_text.tr("|", " ")
array = morse_text.split(" ").map { |word| encode_word.invert[word].upcase }
array.join
end
def encode_word
morse_code = {
"a" => ".-",
"b" => "-...",
"c" => "-.-.",
"d" => "-..",
"e" => ".",
"f" => "..-.",
"g" => "--.",
"h" => "....",
"i" => "..",
"j" => ".---",
"k" => "-.-",
"l" => ".-..",
"m" => "--",
"n" => "-.",
"o" => "---",
"p" => ".--.",
"q" => "--.-",
"r" => ".-.",
"s" => "...",
"t" => "-",
"u" => "..-",
"v" => "...-",
"w" => ".--",
"x" => "-..-",
"y" => "-.--",
"z" => "--..",
" " => "|"
}
end
I'm struggling in convert the pipe into a blank space so I can get the desire result.
Upvotes: 3
Views: 183
Reputation: 110725
Simply use the form of String#gsub that employs a hash for making substitutions.
If the variable morse_code
holds your hash, with the additional key_value pair ""=>" "
, compute the following hash.
decoding_map = morse_code.invert.transform_values(&:upcase)
#=> {".-"=>"A", "-..."=>"B", "-.-."=>"C", "-.."=>"D", "."=>"E",
# ...
# "-..-"=>"X", "-.--"=>"Y", "--.."=>"Z", "|"=>" ", , " "=>""}
Then
morse_text = '.... ..|--. ..- -.-- ...'
morse_text.gsub(/[| ]|[.-]+/, decoding_map)
#=> "HI GUYS"
The regular expression reads, "match a pipe or space or a mix of one or more periods or hyphens".
Upvotes: 1
Reputation: 10546
The issue is that you're converting the pipe to a space which means you lose the unique separator for words and treat it as just a standard separator of characters. Instead, split by the pipe and operate on an array of words:
def decode(morse_text)
# Split the morse code into an array of encoded words
encoded_words = morse_text.split('|')
# Decode each word letter by letter
decoded_words = encoded_words.map do |word|
word.split(' ').map { |letter| encode_word.invert[letter].upcase }
end
# Join each decoded word into a string
joined_words = decoded_words.map { |word| word.join }
# Join each word into a single string
decoded_text = joined_words.join(' ')
end
The result is:
decode('.... ..|--. ..- -.-- ...')
=> "HI GUYS"
Upvotes: 2