Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created November 27, 2012 20:36
Show Gist options
  • Save follesoe/4156846 to your computer and use it in GitHub Desktop.
Save follesoe/4156846 to your computer and use it in GitHub Desktop.
Early work in progress for a simple genetic algorithm simulation

Work in progress

Code from a coding session 27. nov, playing with Clojure after reading the Clojure chapter in the 7 Languages in 7 Weeks book.

The idea is to build a simple simulation for a genetic algorithm. The task is to generate the best program to solve the task of eating as much food as possible in a maze, without stepping on a mine.

We didn't get too far on the task, as none of us had much Clojure experience. Currently we have two instructions, walk and turn. The instructions can be added in a list, and then executed on the world. The idea is to add more instructions, such as look/if and jump/goto, and then generate multiple programs to run in a simulation, and then mutate towards finding the program capable of eating the most food.

Putting the code up here in case we plan to continue on the project some other time.

(ns gensim.core)
(def size 10)
(defn cls [] (print "\033\143"))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn is-player? [cell]
(cond
(= cell :up) true
(= cell :down) true
(= cell :right) true
(= cell :left) true
:else false))
(defn find-player-pos [world]
(first (indices is-player? world)))
(defn turn-me [cell]
(cond
(= cell :up) :right
(= cell :down) :left
(= cell :right) :down
(= cell :left) :up
:else cell))
(defn turn [world]
(mapv turn-me world))
(defn walk [world]
(def pos (find-player-pos world))
(def player (nth world pos))
(def row-number (int (/ pos size)))
(def new-pos (+ (mod (+ pos 1) size) (* row-number size)))
(def empty-world (assoc world pos :empty))
(assoc empty-world new-pos player))
(defn make-cell [n]
(def r (rand-int 100))
(cond
(< r 30) :food
(< r 40) :mine
:else :empty))
(defn print-cell [cell]
(cond
(= cell :up) " ^ "
(= cell :down) " v "
(= cell :left) " < "
(= cell :right) " > "
(= cell :empty) " - "
(= cell :food) " # "
(= cell :mine) " * "))
(defn make-world []
(cons
:up
(map make-cell
(range 1 (* size size)))))
(defn print-world [world]
(Thread/sleep 200)
(loop [w world]
(when (> (count w) 0)
(doseq [i (take size w)] (print (print-cell i)))
(println)
(recur (drop size w)))))
(def program (list
turn
walk
turn
walk
look
turn
walk))
(defn run [program, world]
(loop [w world p program]
(cls)
(print-world w)
(when (> (count p) 0)
(def new-world ((first p) w))
(recur new-world (rest p)))))
(defn -main []
(def world (make-world))
(run program world))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment