Skip to content

Instantly share code, notes, and snippets.

@t-ob
Last active December 12, 2015 05:29
Show Gist options
  • Save t-ob/4722378 to your computer and use it in GitHub Desktop.
Save t-ob/4722378 to your computer and use it in GitHub Desktop.
(defn random-bits []
(->> (repeatedly #(rand-int 2))
(take (+ 5 (rand-int 10)))
vec))
(def config
{:base 2
:codon-bits 8
:point-mutation-rate 1
:crossover-rate 0.3
:duplication-rate 1
:deletion-rate 0.5
:number-of-codons 10})
(defn- maybe? [p]
(< (rand) p))
(def flip-bit (partial bit-xor 1))
(defn lazy-bitstream [bits]
(cycle bits))
(defn codons [bitstream]
(partition (:codon-bits config) bitstream))
(defn to-codons [bits]
(->> bits
lazy-bitstream
codons
(take (:number-of-codons config))))
(defn to-int [bits]
(->> bits
(str/join "")
(#(Integer/parseInt % 2))))
(defn to-bits [i]
(->> (Integer/toBinaryString i)
(map #(- (int %) 48))
(into [])))
(defn mutate-point [bits]
(let [r (/ (:point-mutation-rate config) (count bits))]
(mapv #(if (maybe? r) (flip-bit %) %) bits)))
(defn single-point-crossover [bits1 bits2]
(let [b1-ints (->> bits1 to-codons (mapv to-int))
b2-ints (->> bits2 to-codons (mapv to-int))
cut (->> [b1-ints b2-ints]
(map count)
(apply min)
dec
rand-int
inc)]
(->> [(take cut b1-ints) (drop cut b2-ints)]
(apply concat)
(mapcat to-bits))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment