Skip to content

Instantly share code, notes, and snippets.

@svdberg
Created June 6, 2011 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svdberg/1009867 to your computer and use it in GitHub Desktop.
Save svdberg/1009867 to your computer and use it in GitHub Desktop.
Finding telephone number mnemonics
(ns mnemonics.core
(:require [clojure.string :as str :only (lower-case)])
(:use [clojure.contrib.duck-streams :only (read-lines)]))
(def *number-pairs*
{ 0 "e" 1 "jnq" 2 "rwx" 3 "dsy" 4 "ft" 5 "am" 6 "civ" 7 "bku" 8 "lop" 9 "ghz"})
(defn pair-list
[n cs]
(map #(hash-map % n) cs))
(defn encode
"encode a character by looking up the coressponding number"
[char]
(let [code-table (map #(pair-list (first %) (second %)) *number-pairs*)
ct (reduce merge (flatten code-table))]
(ct char)))
(defn encode-word
"match a word to a (possible) string of digits"
[word]
(map encode word))
(def *word-list*
(read-lines "/usr/share/dict/words"))
(def *word-number-pairs*
(map vector (map encode-word (map str/lower-case *word-list*)) *word-list*))
;stupid brute-force way of finding words.. takes forever on the 24k words
(defn find-words
[number-list lst]
(filter #(= (first %) number-list) lst))
;definition of a multi-map
;(defrecord Multi-map-element [number words])
(def *multi-map* {})
(defn add-to-multimap
[element mmap]
(let [nm (reduce str "" (first element))
elm {nm [(second element)]}]
(merge mmap elm)))
(defn find-in-mmap
[num mmp]
(let [result (get-in mmp [num])]
(if (empty? result)
nil
{num result})))
(defn update-multimap
[element mmap]
(let [nm (reduce str "" (first element))
word (second element)
old-words ((find-in-mmap nm mmap) nm)
new-words (conj old-words word)]
(assoc mmap nm new-words)))
(defn convert-to-multi-map
"takes a map and a multimap, and converts the map to a map with list of words as values"
[mp mmp]
(if (or (nil? mp) (empty? mp)) mmp
(let [elem (first mp)
new-map (if (find-in-mmap (reduce str "" (first elem)) mmp)
(update-multimap (first mp) mmp)
(add-to-multimap (first mp) mmp))]
(recur (rest mp) new-map))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment