Julia Community 🟣

The Julia Geek
The Julia Geek

Posted on

Splitting and Joining Strings to Translate Morse Code πŸ“‡

Splitting and joining strings are two prominent actions in working on textual data. A good example of training these two concepts is to translating Morse codes. For this, we can create a Morse code dictionary like the following one:

codes = Dict(
  ".-"=>"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", ""=>" "
)
Enter fullscreen mode Exit fullscreen mode

So I consider an arbitrary rule that letters should be distinguished by a space and words by two spaces. So I define my morse function that gets an input of type String and another of type Dict{String, String}. First, it splits the input by a space and then translates each segment using the predefined dictionary. Then at the end, I join the content of the translated codes to accomplish the message:

function morse(code::String, dictionary::Dict{String, String})
  splitted = split(code, " ")
  letters = get.(Ref(dictionary), splitted, nothing)
  join(letters)
end
Enter fullscreen mode Exit fullscreen mode

Now I'm ready to use the function:

morse(
  "..  .-.. --- ...- .  .--- ..- .-.. .. .-",
  codes
)

# "I LOVE JULIA"
Enter fullscreen mode Exit fullscreen mode

But you know that Morse codes can also be used to deliver critical messages to the world. Then, do you want to try the translation of the following morse code?

morse(
  ".-- --- -- .- -.  .-.. .. ..-. .  ..-. .-. . . -.. --- --",
  codes
)
Enter fullscreen mode Exit fullscreen mode

Cheers 🍻

Top comments (1)

Collapse
 
ohanian profile image
Steven Siew

You can treat Morse code as a very very weak kind of cryptography. Cryptography for 9 year old kids.