Created
July 26, 2011 19:09
-
-
Save swannodette/1107653 to your computer and use it in GitHub Desktop.
phone_code.clj
This file contains 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
package demo | |
class Coder(words: List[String]) { | |
private val mnemonics = Map( | |
'2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL", | |
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ") | |
private val charCode: Map[Char, Char] = | |
for ((digit, str) <- mnemonics; letter <- str) yield letter -> digit | |
private def wordCode(word: String): String = word.toUpperCase map charCode | |
private val wordsForNum: Map[String, Seq[String]] = (words groupBy wordCode) withDefaultValue List() | |
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 | |
def translate(number: String): Set[String] = encode(number) map (_ mkString " ") | |
} | |
object Coder extends App { | |
val dict = io.Source.fromFile("/usr/share/dict/words") | |
.getLines.filter(_.length > 1).filter(_.matches("[a-zA-Z]+")).toList | |
val coder = new Coder("Scala" :: "rocks" :: dict) | |
println(coder.translate("7225276257")) | |
} |
This file contains 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
(use '[clojure.core.logic prelude nonrel]) | |
(def words (string/split-lines (slurp "/usr/share/dict/words"))) | |
(def mnemonics {\2 "ABC" \3 "DEF" \4 "GHI" \5 "JKL" | |
\6 "MNO" \7 "PQRS" \8 "TUV" \9 "WXYZ"}) | |
(def char-code (into {} (for [[digit string] mnemonics letter string] [letter digit]))) | |
(defn word-code [word] (map char-code (.toUpperCase word))) | |
(defrel wordo ^:index ns ^:index cs) | |
(doseq [word (filter #(<= (count %) 7) words)] (fact wordo (word-code word) word)) | |
(fact wordo '() "") | |
(defn encode [s] | |
(let [s (seq s)] | |
(run* [q] | |
(exist [x y xo yo] | |
(appendo x y s) (wordo x xo) (wordo y yo) | |
(project [xo yo] (== q (apply str xo yo))))))) | |
(comment | |
(encode "6327537") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment