Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. package demo
  2.  
  3. class Coder(words: List[String]) {
  4.  
  5. private val mnemonics = Map(
  6. '2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL",
  7. '6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ")
  8.  
  9. /** Invert the mnemonics map to give a map from chars 'A' ... 'Z' to '2' ... '9' */
  10. private val charCode: Map[Char, Char] =
  11. for ((digit, str) <- mnemonics; letter <- str) yield letter -> digit
  12.  
  13. /** Maps a word to the digit string it can represent, e.g. “Java” -> “5282” */
  14. private def wordCode(word: String): String = word.toUpperCase map charCode
  15.  
  16. /** A map from digit strings to the words that represent them,
  17. * e,g. “5282” -> List(“Java”, “Kata”, “Lava”, ...)
  18. * Note: A missing number should map to the empty set, e.g. "1111" -> List()
  19. */
  20. private val wordsForNum: Map[String, Seq[String]] = (words groupBy wordCode) withDefaultValue List()
  21.  
  22. /** Return all ways to encode a number as a list of words */
  23. def encode(number: String): Set[List[String]] =
  24. if (number.isEmpty) Set(List())
  25. else {
  26. for {
  27. split <- 1 to number.length
  28. word <- wordsForNum(number take split)
  29. rest <- encode(number drop split)
  30. } yield word :: rest
  31. }.toSet
  32.  
  33.  
  34. /** Maps a number to a list of all word phrases that can represent it */
  35. def translate(number: String): Set[String] = encode(number) map (_ mkString " ")
  36. }
  37.  
  38. object Coder extends App {
  39. val dict = io.Source.fromFile("/usr/share/dict/words")
  40. .getLines.filter(_.length > 1).filter(_.matches("[a-zA-Z]+")).toList
  41. val coder = new Coder("Scala" :: "rocks" :: dict)
  42. println(coder.translate("7225276257"))
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement