Created
March 7, 2012 00:57
-
-
Save phaller/1990191 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
/* | |
* Copyright 2011-2012 Typesafe Inc. | |
* | |
* This work is based on the original contribution of WeigleWilczek. | |
* | |
* Unless otherwise agreed, training materials may only be used for | |
* educational and reference purposes by individual named participants | |
* in a training course offered by Typesafe or a Typesafe training partner. | |
* Unauthorized reproduction, redistribution, or use of this material is prohibited. | |
*/ | |
package misc | |
class PhoneMnemonics(words: Set[String]) { | |
val mnemonics = Map( | |
'2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL", | |
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ" | |
) | |
/** | |
* Inverse of the mnemonics map, e.g. 'A' -> '2', 'B' -> '2'. | |
*/ | |
val charCode: Map[Char, Char] = | |
for { | |
digitAndString <- mnemonics | |
letter <- digitAndString._2 | |
} yield letter -> digitAndString._1 | |
/** | |
* Maps a word to its digit representation, e.g. "Java" -> "5282". | |
*/ | |
def wordCode(word: String): String = word.toUpperCase map charCode | |
/** | |
* Groups all words by their number representations, e.g. "5282" -> Set("Java", "Kata", ...). | |
*/ | |
val wordsForNumber: Map[String, Set[String]] = words groupBy wordCode | |
/* | |
Map() ++ (for { | |
word <- words | |
code = wordCode(word) | |
} yield (code, words.filter(w => wordCode(w) == code))) | |
*/ | |
/** | |
* All ways to encode a number as a pharse, i.e. as a sequence of words. | |
*/ | |
def encode(number: String): Set[Seq[String]] = | |
if (number.length() == 0) Set(Seq()) | |
else for { | |
splitPoint <- Set() ++ (1 to number.length) | |
firstWordDigits = number take splitPoint | |
phrase <- encode(number drop splitPoint) | |
word <- wordsForNumber.getOrElse(firstWordDigits, Set()) | |
} yield word +: phrase | |
/** | |
* Maps a number to the set of all phrases that can represent it. | |
*/ | |
def translate(number: String): Set[String] = encode(number) map (_ mkString " ") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment