Skip to content

Instantly share code, notes, and snippets.

@jordanlewis
Created December 7, 2012 04:48
Show Gist options
  • Save jordanlewis/4230827 to your computer and use it in GitHub Desktop.
Save jordanlewis/4230827 to your computer and use it in GitHub Desktop.
Prim's algorithm
(defn prim [graph]
(let [sortedgraph (sort-by #(nth % 2) graph)
startv (->> graph (map #(take 2 %)) flatten set)]
((fn [v e]
(if (= v startv) (reduce + (map #(nth % 2) e))
(let [minedge (first (filter (fn [e] (= 1 (count (filter identity (map #(v (nth e %)) '(0 1)))))) sortedgraph))]
(recur (apply conj v (take 2 minedge)) (conj e minedge)))))
#{(ffirst graph)} #{})))
(def g [['a 'b 7] ['a 'd 5] ['b 'c 8] ['b 'e 7] ['b 'd 9] ['c 'e 5] ['d 'e 15] ['d 'f 6] ['e 'g 9] ['e 'f 8] ['f 'g 11]])
;; example graph from wikipedia's page on Prim's algorithm
(prim g)
;; -> 39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment