Skip to content

Instantly share code, notes, and snippets.

@newmen
Created October 23, 2018 12:40
Show Gist options
  • Save newmen/56f7b40ecee7abaefdf874fb33e92a66 to your computer and use it in GitHub Desktop.
Save newmen/56f7b40ecee7abaefdf874fb33e92a66 to your computer and use it in GitHub Desktop.
(ns ideal.tools.graph)
(defn add-edge
[graph v w]
(update graph v (fnil conj #{}) w))
(defn all-children
[graph key]
(if-let [first-children (get graph key)]
(into #{}
(concat first-children
(mapcat #(all-children graph %) first-children)))
#{}))
(defn all-vertices
[graph]
(into #{}
(concat (keys graph)
(apply concat (vals graph)))))
(defn all-edges
[graph]
(into #{}
(reduce-kv (fn [acc k vs]
(concat acc (map #(vector k %) vs)))
#{}
graph)))
(defn invert
[graph]
(into {}
(reduce-kv (fn [acc k vs]
(reduce #(add-edge %1 %2 k) acc vs))
{}
graph)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment