Created
May 28, 2011 17:42
-
-
Save oluies/997068 to your computer and use it in GitHub Desktop.
coder
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
class Coder(words: List[String]) { | |
def ?? = error("not implemented" ) | |
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' */ | |
val charCode: Map[Char, Char] = | |
for( (k,v) <- mnemonics; letter <- v ) yield (letter -> k) | |
/** Maps a word to the digit string it can represent, e.g. “Java” -> “5282” */ | |
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) | |
/** Return all ways to encode a number as a list of words */ | |
def encode(number: String): Set[List[String]] = { | |
if(number.isEmpty) Set(Nil) | |
else { | |
val splits = Range(0,number.length).toSet | |
for{idx <- splits | |
val (prefix, rest) = number.splitAt(idx) | |
if wordsForNum.isDefinedAt(prefix) | |
firstWord <- wordsForNum(prefix) | |
subSolution <- encode(rest) | |
} yield firstWord :: subSolution | |
} | |
} | |
/** Maps a number to a list of all word 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