Created
June 24, 2010 21:43
-
-
Save swannodette/452032 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns cellular-automata-basic) | |
(set! *warn-on-reflection* true) | |
(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])) | |
(defrecord CellularAutomata [^long nrows ^long ncols ^longs cells ^longs others] | |
Automata | |
(update [this] (CellularAutomata. ncols nrows | |
(amap cells idx result | |
(let [idx idx | |
i (unchecked-remainder-long idx ncols) | |
j (if (zero? idx) 0 (unchecked-divide-long idx ncols))] | |
(aset result idx (.urEightNeighMinmax this i j)))) | |
others)) | |
AutomataOps | |
(getCell [this i j] (aget cells (+ (unchecked-multiply-long 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