Skip to content

Instantly share code, notes, and snippets.

@dawranliou
Created May 1, 2018 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dawranliou/00cd6c90da54a2a1bed8500108a351e2 to your computer and use it in GitHub Desktop.
Save dawranliou/00cd6c90da54a2a1bed8500108a351e2 to your computer and use it in GitHub Desktop.
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