Skip to content

Instantly share code, notes, and snippets.

@irpap
Last active December 20, 2015 14:39
Show Gist options
  • Save irpap/6148006 to your computer and use it in GitHub Desktop.
Save irpap/6148006 to your computer and use it in GitHub Desktop.
Code from the Functional Programming in Scala session.
import org.scalatest.FunSuite
class MnemonicsDemoSolution extends FunSuite {
class Coder(val words: List[String]) {
val mnem = Map(
'2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL",
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ")
/** Invert the mnem map to give a map from chars 'A'...'Z' to '2'...'9' */
val charCode: Map[Char, Char] =
for ((digit, word) <- mnem; letter <- word)
yield (letter -> digit)
//for ((digit, word) <-mnem; letter <- word)) yield letter -> digit
/** Maps a word to the digit string it can represent e.g. "Java" -> "5282" */
def wordCode(word: String): String = word.toUpperCase.map(charCode(_))
/** A map from digit strings to the words that represent them, e.g. "5282" -> List("Java", "Kata", "Lava", ...) */
val wordsForNum: Map[String, Seq[String]] = words.groupBy(word => wordCode(word)) withDefaultValue List()
/** Return all ways to encode a number as a list of words */
def encode(number: String): Set[List[String]] = {
if (number.isEmpty) Set(List())
else
for {
splitPoint <- (1 to number.length)
word <- wordsForNum(number take splitPoint)
rest <- encode(number drop splitPoint)
} yield word :: rest
}.toSet
/** Maps a number to all the word phrases that can represent it */
def translate(number: String): Set[String] = encode(number) map (_ mkString " ")
}
test("mnemonics") {
val dict: List[String] = "rocks" :: io.Source.fromFile("/usr/share/dict/words")
.getLines.filter(_.length > 2).filter(_.matches("[a-zA-Z]+")).toList
val coder = new Coder(dict)
val mnemonics = coder.translate("7225276257")
println(mnemonics)
assert(mnemonics.contains("scala rocks") == true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment