Skip to content

Instantly share code, notes, and snippets.

@maruks
Created October 31, 2012 23:09
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 maruks/3990536 to your computer and use it in GitHub Desktop.
Save maruks/3990536 to your computer and use it in GitHub Desktop.
code from LSCC October Hands-on session - Experimenting with self organized criticality
(def size 50)
(def avalanche-threshold 3)
(def empty-table (vec (repeat size (vec (repeat size 0)))))
(defn adjacent-cells [x y]
(filter #(and (not (neg? (first %))) (not (neg? (second %))) (< (first %) size) (< (second %) size))
(list [x (inc y)] [x (dec y)] [(inc x) y] [(dec x) y])))
(defn avalanche [table cells-to-increment avalanches]
(if-not (seq cells-to-increment)
[table avalanches]
(let [cell (first cells-to-increment)
new-table (update-in table cell inc)
is-avalanche (> (get-in new-table cell) avalanche-threshold)]
(if is-avalanche
(recur (assoc-in new-table cell 0) (concat (apply adjacent-cells cell) (rest cells-to-increment)) (inc avalanches))
(recur new-table (rest cells-to-increment) avalanches)))))
(defn add-grain [x y table]
(avalanche table (list [x y]) 0))
(defn add-many-grains [table grains total avalanches]
(if (zero? grains) (reverse avalanches)
(let [[new-table num-of-avalanches] (add-grain (rand-int size) (rand-int size) table)]
(recur new-table (dec grains) total (cons [(- total (dec grains)) num-of-avalanches] avalanches)))))
(defn get-stats [num-of-grains]
(add-many-grains empty-table num-of-grains num-of-grains '()))
(defn get-freqs [num-of-grains]
(frequencies (map second (get-stats num-of-grains))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment