Last active
December 12, 2015 05:29
-
-
Save t-ob/4722378 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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