-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decode the Morse code.rb
67 lines (49 loc) · 2.59 KB
/
Decode the Morse code.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
=begin
In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly
superceded by voice and digital data communication channels, it still has its use in some
applications around the world.
The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the
letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−. The Morse code
is case-insensitive, traditionally capital letters are used. When the message is written in Morse
code, a single space is used to separate the character codes and 3 spaces are used to separate words.
For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·.
NOTE: Extra spaces before or after the code have no meaning and should be ignored.
In addition to letters, digits and some punctuation, there are some special service codes, the most
notorious of those is the international distress signal SOS (that was first issued by Titanic), that
is coded as ···−−−···. These special codes are treated as single special characters, and usually are
transmitted as separate words.
Your task is to implement a function decodeMorse(morseCode), that would take the morse code as input
and return a decoded human-readable string.
For example:
decodeMorse('.... . -.-- .--- ..- -.. .')
#should return "HEY JUDE"
The Morse code table is preloaded for you as a dictionary, feel free to use it. In CoffeeScript, C++,
JavaScript, PHP, Python, Ruby and TypeScript, the table can be accessed like this: MORSE_CODE['.--'],
in Java it is MorseCode.get('.--'), in C# it is MorseCode.Get('.--'), in Haskell the codes are in a Map
String String and can be accessed like this: morseCodes ! ".--", in Elixir it is morse_codes variable.
All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions.
In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly
because otherwise the engine would simply ignore the tests, resulting in a "valid" solution.
Good luck!
#alternative solution (not mine)
def decodeMorse(morseCode)
morseCode.strip.split(" ").map { |w| w.split(" ").map { |c| MORSE_CODE[c] }.join }.join(" ")
end
=end
def decodeMorse(morseCode)
message = ""
morseCode = morseCode.strip.gsub(" ", " s ").split(" ")
for code in morseCode
MORSE_CODE.each do |k,v|
if code == k
message.concat(v)
elsif code == "s"
message.concat(" ")
break
else
message
end
end
end
message.upcase
end