Skip to content

Instantly share code, notes, and snippets.

@pavelborisov
Created December 10, 2015 14:59
Show Gist options
  • Select an option

  • Save pavelborisov/a75ea35a21e8c63957df to your computer and use it in GitHub Desktop.

Select an option

Save pavelborisov/a75ea35a21e8c63957df to your computer and use it in GitHub Desktop.
// 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('0' -> " 0", '*' -> "-", '1' -> "'.,?!@1", '2' -> "2ABC", '3' -> "DEF3", '4' -> "GHI4", '5' -> "JKL5", '6' -> "MNO6", '7' -> "PQRS7", '8' -> "TUV8", '9' -> "WXYZ9")
/*
Получаем на основе карты `mnemonics` отношение Цифра -> Символ
*/
val charCode: Map[Char, Char] = mnemonics.flatMap{ case (k,v) => v.toList.map( (_, k) ) }
/*
Кодируем word в набор цифр
*/
def wordCode(word: String): String = word.toUpperCase.toList.map( charCode ).mkString
wordCode("Scala mnemonics")
/*
Преобразуем словарь `words` в отношение код -> варианты слов, кодируемые этим кодом
*/
val wordsForNum: Map[String, Seq[String]] = words.groupBy( wordCode ).withDefaultValue(Seq.empty[String])
wordsForNum("72252")
wordsForNum("663666427")
/*
Получаем на основе полученного кода `numbers` набор всех возможных вариантов предложений
Подсказка: используйте for-expression
*/
def encode(number: String): Set[List[String]] = {
if( number.isEmpty )
Set( List.empty[String] )
else
(for( i <- 1 to number.length;
code = number.substring(0, i);
word <- wordsForNum(code);
wordList <- encode( number.substring( i ) )
) yield {
word :: wordList
}).toSet
}
encode("72252")
encode("72252663666427")
def translate(number: String): Set[String] = encode(number) map (_ mkString " ")
translate("72252663666427")
translate("72252663666427").contains("Scala mnemonics")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment