Created
May 1, 2018 23:10
-
-
Save dawranliou/00cd6c90da54a2a1bed8500108a351e2 to your computer and use it in GitHub Desktop.
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
package week6 | |
import scala.io.Source | |
object mnemonics { | |
val in = Source.fromURL("https://raw.github.com/jpalmour/progfun/master/forcomp/src/main/resources/forcomp/linuxwords.txt") | |
val words = in.getLines.toList filter (word => word forall (chr => chr.isLetter)) | |
val mnem = Map( | |
'2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL", | |
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ") | |
val charCode: Map[Char, Char] = | |
for ((digit, str) <- mnem; ltr <- str) yield ltr -> digit | |
def wordCode(word: String): String = | |
word.toUpperCase map charCode | |
val wordsForNum: Map[String, Seq[String]] = | |
words groupBy wordCode withDefaultValue Seq() | |
def encode(number: String): Set[List[String]] = | |
if (number.isEmpty) Set(List()) | |
else { | |
for { | |
split <- 1 to number.length | |
word <- wordsForNum(number take split) | |
rest <- encode(number drop split) | |
} yield word :: rest | |
}.toSet | |
encode("847825") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment