Skip to content

Instantly share code, notes, and snippets.

@hypirion
Forked from mmower/gist:10ca3d5acaf7a8033916
Last active December 17, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypirion/3704bbe71921b73e694d to your computer and use it in GitHub Desktop.
Save hypirion/3704bbe71921b73e694d to your computer and use it in GitHub Desktop.
;; 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