DEV Community

loading...

Discussion on: Daily Challenge #254 - The Vowel Code

Collapse
awwsmm profile image
Andrew (he/him)

A nice, simple, symmetric solution in Scala:

val toIndex = Map('a' -> '1', 'e' -> '2', 'i' -> '3', 'o' -> '4', 'u' -> '5')
val toVowel = toIndex map { _.swap }

def encode (str: String): String = str.map(ch => if (toIndex.contains(ch)) toIndex(ch) else ch).mkString
def decode (str: String): String = str.map(ch => if (toVowel.contains(ch)) toVowel(ch) else ch).mkString

Tests:

scala> decode("h2ll4")
res2: String = hello

scala> encode("hello")
res3: String = h2ll4

scala> decode("h3 th2r2")
res4: String = hi there

scala> decode("h2ll4")
res5: String = hello

scala> encode("This is an encoding test.")
res6: String = Th3s 3s 1n 2nc4d3ng t2st.

scala> encode("How are you today?")
res7: String = H4w 1r2 y45 t4d1y?