Created
December 10, 2015 13:39
-
-
Save rgordeev/ebc410d2e0d24b999092 to your computer and use it in GitHub Desktop.
scala homework #5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Lutz Prechelt: An Empirical Comparison of Seven Programming Languages | |
val in = scala.io.Source.fromURL("http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/linuxwords.txt") | |
val words: List[String] = in.getLines().toList | |
val mnemonics: Map[Char, String] = Map('2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL", '6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ", '0' -> " ") | |
/* | |
Получаем на основе карты `mnemonics` отношение Цифра -> Символ | |
*/ | |
val charCode: Map[Char, Char] = for ((d, str) <- mnemonics; ch <- str) yield (ch, d) | |
/* | |
Кодируем word в набор цифр | |
*/ | |
def wordCode(word: String): String = word.map(ch => charCode.withDefaultValue('0')(ch.toUpper)) | |
wordCode("Scala mnemonics") | |
/* | |
Преобразуем словарь `words` в отношение код -> варианты слов, кодируемые этим кодом | |
*/ | |
val wordsForNum: Map[String, Seq[String]] = words.groupBy(wordCode).withDefaultValue(List()) | |
wordsForNum("72252") | |
wordsForNum("663666427") | |
/* | |
Получаем на основе полученного кода `numbers` набор всех возможных вариантов предложений | |
Подсказка: используйте for-expression | |
*/ | |
def encode(number: String): Set[Seq[String]] = number.permutations.map(str => wordsForNum(str)).toSet | |
// слишком длинный код для поиска всех возможных сочетаний | |
//72252663666427 | |
encode("7225") | |
def translate(number: String): Set[String] = encode(number).map (_.mkString(" ")) | |
translate("7225")//.contains("Scala mnemonics") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment