Skip to content

Instantly share code, notes, and snippets.

@arnab
Created October 11, 2013 07:18
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 arnab/6930806 to your computer and use it in GitHub Desktop.
Save arnab/6930806 to your computer and use it in GitHub Desktop.
From the Joy of Clojure, showing off the succinctness and power of Clojure.
;; Now I know what dense means :)
(defn neighbors
([size yx] (neighbors [[-1 0] [1 0] [0 -1] [0 1]]
size yx))
([deltas size yx]
(filter (fn [new-yx]
(every? #(< -1 % size) new-yx))
(map #(vec (map + yx %))
deltas))))
@arnab
Copy link
Author

arnab commented Oct 11, 2013

Takes a size and a coordinate yx and returns the neighbors of that cell in a matrix. This version returns the max 4 up/down/right/left neighbors.

(neighbors 4 [0 1])
;; ([1 1] [0 0] [0 2])

@arnab
Copy link
Author

arnab commented Oct 11, 2013

For comparision, here's some code I wrote in Ruby a while back to do a similar thing: https://github.com/arnab/game_of_life/blob/master/lib/game_of_life/board.rb#L179-L188. And that doesn't reject illegal cells yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment