Skip to content

Instantly share code, notes, and snippets.

@yayitswei
Created September 6, 2012 22:16
Show Gist options
  • Select an option

  • Save yayitswei/3660803 to your computer and use it in GitHub Desktop.

Select an option

Save yayitswei/3660803 to your computer and use it in GitHub Desktop.
adjacent
(defn two->one [[x y] [w h]]
{:pre [(< x w) (< y h)]}
(+ x (* y w)))
(defn one->two [i [w h]]
{:pre [(< i (* w h))]}
[(mod i w) (int (/ i w))])
(defn valid-space [[x y] [w h]]
(and (<= 0 x) (<= 0 y) (< x h) (< y w)))
(defn adjacent [i [w h :as size]]
(let [[x y] (one->two i size)]
(for [tx (range (dec x) (+ x 2))
ty (range (dec y) (+ y 2))]
(when (and (valid-space [tx ty] size)
(not (and (= x tx) (= y ty))))
(two->one [tx ty] size)))))
(defn adjacent-clean [i size]
(sort (filter identity (adjacent i size))))
;; test
(let [size [3 3]]
(assert (= '(1 3 4) (adjacent-clean 0 size)))
(assert (= '(0 2 3 4 5) (adjacent-clean 1 size)))
(assert (= '(3 4 7) (adjacent-clean 6 size))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment