/gist:3704bbe71921b73e694d Secret
Last active
December 17, 2015 18:59
-
-
Save hypirion/3704bbe71921b73e694d to your computer and use it in GitHub Desktop.
This file contains 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
;; First cut at generating & evolving random boolean networks | |
;; in Clojure. I'm still learning CLJ so please be gentle... | |
(defn or-oper [a b] (or a b)) | |
(defn and-oper [a b] (and a b)) | |
(defn xor-oper [a b] (or (and a (not b)) (and (not a) b))) | |
(defn random-oper [] | |
(rand-nth [or-oper and-oper xor-oper])) | |
;; rand-nth returns one random element in the coll | |
(defn random-state [] | |
(rand-nth [true false])) ;; rand-nth here too | |
(defn potential-connections [n size exc] | |
(let [pool (shuffle (filter #(not= exc %1) (range size)))] | |
(take n pool))) | |
(defn make-cell-func [size] | |
(fn [n] | |
{:idx n ;; {} instead of hash-map | |
:state (random-state) | |
:connections (potential-connections 2 size n) | |
:oper (random-oper)})) | |
(defn make-network [dim] | |
(let [size (* dim dim) | |
make-cell (make-cell-func size)] | |
(map make-cell (range size)))) ;; #(make-cell %1) -> make-cell | |
(defn evolve-cell [cell network] | |
(let [connections (map #(nth network %1) (:connections cell)) | |
operands (map :state connections) ;; #(:state %1) -> :state | |
new-state (apply (:oper cell) operands)] | |
(assoc cell :state new-state))) ;; cell is immutable, use assoc for new state | |
(defn evolve-network [network] | |
(for [cell network] ;; for every cell in the network, evolve it and return the new cells | |
(evolve-cell cell network))) | |
(def first-gen-net (make-network 8)) | |
(def second-gen-net (evolve-network first-gen-net)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment