Skip to content

Instantly share code, notes, and snippets.

@mariofusco
Created June 12, 2011 16:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariofusco/1021723 to your computer and use it in GitHub Desktop.
Save mariofusco/1021723 to your computer and use it in GitHub Desktop.
Encodes a number in one (or more) list of words corresponding to its phone mnemonic code
class MnemonicsCoder(words: List[String]) {
private val mnemonics = Map('2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL",
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ")
/** Invert the mnemonics map to give a map from chars 'A' ... 'Z' to '2' ... '9' */
private val charCode: Map[Char, Char] =
for ((digit, str) <- mnemonics; letter <- str) yield (letter -> digit)
/** Maps a word to the digit string it can represent */
private def wordCode(word: String): String =
word.toUpperCase map charCode
/** A map from digit strings to the words that represent them,
* e,g. “5282” ‐> Set(“Java”, “Kata”, “Lava”, ...) */
private val wordsForNum: Map[String, List[String]] =
(words groupBy wordCode) withDefaultValue List.empty
/** Return all ways to encode a number as a list of words */
private 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 a list of all word phrases that can represent it */
def translate(number: String): Set[String] =
encode(number) map (_ mkString " ")
}
@JanxSpirit
Copy link

Excellent! I've been meaning to write this up myself. Thanks for this Mario.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment