Skip to content

Instantly share code, notes, and snippets.

@cshepp
Last active August 29, 2015 14:17
Show Gist options
  • Save cshepp/fe711291767da39da88e to your computer and use it in GitHub Desktop.
Save cshepp/fe711291767da39da88e to your computer and use it in GitHub Desktop.
(defn find-all-cycles [a b]
"finds all possible cycles in the parents"
(loop [idx 0
cyl (order-preserving-set)]
(let [c (find-cycle a b idx)]
(if (= idx (count a))
(vec (seq cyl))
(recur (inc idx) (into cyl [c]))))))
(defn find-cycle [a b seed]
"finds a single cycle in the parents
starting at the seed index"
(loop [coll (mapv vector a b)
cyl #{}
cur (get-in coll [seed 0])]
(let [idx (first (keep-indexed #(if (= (first %2) cur) %1) coll))]
(if (nil? idx)
(vec cyl)
(recur (vec-remove coll idx)
(into cyl (nth coll idx))
(last (nth coll idx)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment