Skip to content

Instantly share code, notes, and snippets.

@bodil
Created April 1, 2012 00:19
Show Gist options
  • Save bodil/2269966 to your computer and use it in GitHub Desktop.
Save bodil/2269966 to your computer and use it in GitHub Desktop.
Clojure solution for http://addagram.mytestbench.com/ with ~1s execution time.
(ns addagram.core
(:use [clojure.test]
[clojure.java.io :only [reader]]))
(with-test
(defn sort-largest [l]
(sort-by #(- (count %)) l))
(is (= ["blerk" "quux" "foo" "bar"]
(sort-largest ["foo" "quux" "bar" "blerk"]))))
(def words (delay (sort-largest (line-seq (reader "WORD.LST")))))
(def anagram-map
(delay
(loop [d {} w @words]
(if (seq w)
(recur (assoc d (sort (first w)) (first w)) (rest w))
d))))
(defn first-anagram [word] (@anagram-map (sort word)))
(with-test
(defn drop-one [word]
(for [i (range (count word))]
(str (apply str (take i word))
(apply str (drop (inc i) word)))))
(is (= '("hai" "oai" "ohi" "oha") (drop-one "ohai"))))
(defn addagram-reduction [word]
(first (filter string? (map first-anagram (drop-one word)))))
(defn addagram [word]
(loop [current word words ()]
(if (< (count current) 4) (conj words current)
(if-let [next (addagram-reduction current)]
(recur next (conj words current))
nil))))
(defn longest-addagram []
(first (remove nil? (pmap addagram @words))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment