Skip to content

Instantly share code, notes, and snippets.

@swannodette
Created May 31, 2010 17:22
Show Gist options
  • Save swannodette/420036 to your computer and use it in GitHub Desktop.
Save swannodette/420036 to your computer and use it in GitHub Desktop.
(ns cellular-automata-basic)
(definterface AutomataOps
(^long getCell [^long i ^long j])
(^long sumEightNeighbors [^long i ^long j])
(^long urEightNeighMinmax [^long i ^long j])
(^long rule [^long i ^long j]))
(defprotocol Automata
(update [this]))
(deftype CellularAutomata [^long nrows ^long ncols ^longs cells ^longs others]
Automata
(update [this] (CellularAutomata. ncols nrows
(amap cells idx result
(let [idx (long idx)
i (unchecked-remainder idx ncols)
j (if (zero? idx) (long 0) (unchecked-divide idx ncols))]
(aset result idx (.urEightNeighMinmax this i j))))
others))
AutomataOps
(getCell [this i j] (aget cells (+ (unchecked-multiply i ncols) j)))
(sumEightNeighbors [this i j]
(-> (.getCell this (dec i) (dec j))
(+ (.getCell this (dec i) j))
(+ (.getCell this (dec i) (inc j)))
(+ (.getCell this i (inc j)))
(+ (.getCell this (inc i) (inc j)))
(+ (.getCell this (inc i) j))
(+ (.getCell this (inc i) (dec j)))
(+ (.getCell this i (dec j)))))
(urEightNeighMinmax [this i j]
(if (or (= i (dec nrows)) (zero? i) (= j (dec ncols)) (zero? j))
(.getCell this i j)
(let [sum (.sumEightNeighbors this i j)]
(if (and (>= sum (aget others 0)) (<= sum (aget others 1)))
(aget others 2)
(.getCell this i j))))))
(defn random-ca [nrows ncols]
(CellularAutomata. nrows ncols
(let [a (longs (make-array Long/TYPE (* nrows ncols)))]
(amap a i result
(aset result i (long (rand-int 2)))))
(long-array [2 5 1])))
(def a (random-ca 2000 2000))
(def b (random-ca 500 500))
(comment
(dotimes [_ 100]
(time
(dotimes [_ 1]
(update b))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment