Skip to content

Instantly share code, notes, and snippets.

@cshepp
Created March 22, 2015 23:37
Show Gist options
  • Save cshepp/1e32a869c94dab510144 to your computer and use it in GitHub Desktop.
Save cshepp/1e32a869c94dab510144 to your computer and use it in GitHub Desktop.
(map cycle-crossover (pair population))
(defn pair [vec]
"splits a 1d array into a 2d array of pairs"
(mapv (fn [i] (subvec vec i (+ 2 i)))
(map #(* 2 %)
(range (/ (count vec) 2)))))
(defn cycle-crossover [[a b]]
"returns both permuations of the parents'
cycle crossover (changed ordering)"
(let [cycles (find-all-cycles a b)
c1 (make-child [a b] cycles)
c2 (make-child [b a] cycles)]
[c1 c2]))
(defn make-child [parents cycles]
"combines parents using cycle crossover"
(loop [res (vec (repeat 10 nil))
idx 0]
(if (= idx (count cycles))
res
(recur (reduce (fn [v e] (assoc v (first e) (last e)))
res
(map (fn [i] [(.indexOf (nth parents (mod idx 2)) i) i])
(nth cycles idx)))
(inc idx)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment