Skip to content

Instantly share code, notes, and snippets.

@scottdw
Created July 11, 2011 14:59
Show Gist options
  • Save scottdw/1076028 to your computer and use it in GitHub Desktop.
Save scottdw/1076028 to your computer and use it in GitHub Desktop.
(defn neighbours-fn [w h n]
(letfn [(has-w [i] (not (zero? (rem i w))))
(pos-w [i] (dec i))
(has-n [i] (>= i w))
(pos-n [i] (- i w))
(has-e [i] (not (zero? (rem (inc i) w))))
(pos-e [i] (inc i))
(has-s [i] (< i (* w (dec h))))
(pos-s [i] (+ i w))]
(let [pred-pos-m {:w [has-w pos-w]
:n [has-n pos-n]
:e [has-e pos-e]
:s [has-s pos-s]
:nw [#(and (has-n %) (has-w %)) (comp pos-w pos-n)]
:ne [#(and (has-n %) (has-e %)) (comp pos-e pos-n)]
:sw [#(and (has-s %) (has-w %)) (comp pos-w pos-s)]
:se [#(and (has-s %) (has-e %)) (comp pos-e pos-s)]}
j (apply juxt (map #(let [[pred pos] (pred-pos-m %)]
(fn [i] (if (pred i) (pos i) -1)))
n))]
(fn [i] (filter (complement neg?) (j i))))))
(defn xy-idx-fn [w]
(fn [x y]
(+ (* w y) x)))
(defn idx-xy-fn [w]
(fn [i]
(let [y (quot i w)
x (rem i w)]
[x y])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment