Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2011 06:39
Show Gist options
  • Save anonymous/1446297 to your computer and use it in GitHub Desktop.
Save anonymous/1446297 to your computer and use it in GitHub Desktop.
;; flengyel's solution to Word Chains
;; https://4clojure.com/problem/82
(fn [wordset] (letfn [(patronize [s] (re-pattern (apply str (interpose ".{0,1}" (map str (vec s))))))
(onediff? [s t n] (let [v (vec s)
w (vec t)]
(= 1 (reduce + (for [i (range n)] (if (= (v i) (w i)) 0 1))))))
(linked? [s t]
(let [a (count s)
b (count t)]
(cond
(= a b) (onediff? s t a)
(= (inc a) b) (= 1 (count (re-seq (patronize s) t)))
(= (inc b) a) (= 1 (count (re-seq (patronize t) s)))
:else false)))
(compose [p q]
(if (and (linked? (last p) (first q))
(empty? (clojure.set/intersection (set p) (set q)))
(not= (first p) (last q)))
(vec (concat p q))))
(str2path [s]
(set (map (fn [i] [i]) (vec s))))
(compose-paths [S T]
(->> (for [p (vec S) q (vec T)] (compose p q))
(filter identity) (set)))]
(let [pathset (str2path wordset)
n (count wordset)]
(not (empty? (nth (iterate (partial compose-paths pathset) pathset) (dec n)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment