Skip to content

Instantly share code, notes, and snippets.

@pchrysa
Last active August 3, 2017 13:27
Show Gist options
  • Save pchrysa/bb0ed1ba59abaa301b8786a8167ae63e to your computer and use it in GitHub Desktop.
Save pchrysa/bb0ed1ba59abaa301b8786a8167ae63e to your computer and use it in GitHub Desktop.
Convert text to morse code in Kotlin
/*
Write a function to convert a string given by the user, to the respective morse code sequence.
Morse code https://en.wikipedia.org/wiki/Morse_code
Example:
User Input: Hello
Output: .... . .-.. .-.. ---
*/
fun main(args: Array<String>) {
textToMorse("Hello")
}
fun textToMorse(s: String) : String {
val morseArr = s.map{value -> convertCharToMorse(value)}
println(morseArr.joinToString(" "))
return s
}
fun convertCharToMorse(c : Char) = when (c.toLowerCase()) {
'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' -> "-----"
else -> throw IllegalArgumentException("Not all characters are valid")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment