Skip to content

Instantly share code, notes, and snippets.

@osfameron
Last active July 5, 2017 01:47
Show Gist options
  • Select an option

  • Save osfameron/ee745e72238fa01ed66a61d116753bef to your computer and use it in GitHub Desktop.

Select an option

Save osfameron/ee745e72238fa01ed66a61d116753bef to your computer and use it in GitHub Desktop.
Neighbours in clojure - simple & overengineered solutions
(defn neighbours-simple [[x y]]
#{[(dec x) (dec y)] [x (dec y)] [(inc x) (dec y)]
[(dec x) y ] [(inc x) y]
[(dec x) (inc y)] [x (inc y)] [(inc x) (inc y)]})
(defn neighbours-zipped [[x y]]
(let [axis (juxt dec identity inc)]
(clojure.set/difference
(set (mapcat (partial map vector)
(repeat (axis x))
(map repeat (axis y))))
#{[x y]})))
; amalloy suggests (but with let-before-fn, for performance, which looks weird to me)
; NB: ordering of 0 unit first + `rest` removes original pos
(defn neighbours-amalloy [pos]
(let [units [0 1 -1]
deltas (rest (for [dx units, dy units] [dx dy]))
+pos (partial map + pos)]
(set (map +pos deltas))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment