Skip to content

Instantly share code, notes, and snippets.

@arnab arnab/neighbors.clj
Created Oct 11, 2013

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.