DEV Community

Discussion on: Daily Challenge #23 - Morse Code Decoder

Collapse
 
mwlang profile image
Michael Lang

Ruby Language

The problem definition was initially tripping because it appeared to somehow render "HEY JUDE" without some sort of demarcation that indicated a space between words since HTML rendering removes extra spacing. However, opening and viewing the HTML source revealed there was indeed multiple spaces between the words. In this implementation, two or more spaces represents a "pause" which is the morse standard for recognizing word breaks.

Code with Specs

MORSE_CODE = Hash[*%w/
  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 --..  1 .---- 2 ..--- 3 ...-- 4 ....-
  5 ..... 6 -.... 7 --... 8 ---.. 9 ----. 0 -----
/].invert.freeze

def decode_morse str
  words = str.to_s.split(/\s{2,}/)
  words.map{|w| w.split(" ").map{|mc| MORSE_CODE[mc]}.join}.join " "
end

require "spec"

describe "#decode_morse" do
  it { expect(decode_morse nil).to eq "" }
  it { expect(decode_morse "").to eq "" }
  it { expect(decode_morse ".").to eq "E" }
  it { expect(decode_morse ". ").to eq "E" }
  it { expect(decode_morse "... --- ...").to eq "SOS" }
  it { expect(decode_morse "- . ... - .. -. --.  .----  ..---  ...--").to eq "TESTING 1 2 3" }
  it { expect(decode_morse ".... . -.-- .--- ..- -.. .").to eq "HEYJUDE" }
  it { expect(decode_morse ".... . -.--   .--- ..- -.. .").to eq "HEY JUDE" }
  it { expect(decode_morse "-- --- .-. ... .    -.-. --- -.. .").to eq "MORSE CODE" }
end

output

>> rspec morse_code.rb
.........

Finished in 0.00551 seconds (files took 0.15391 seconds to load)
9 examples, 0 failures