Skip to content

Instantly share code, notes, and snippets.

@devstopfix
Created August 18, 2016 13:59
Show Gist options
  • Save devstopfix/b397424e9b39396ca0abaf6b3b2c0707 to your computer and use it in GitHub Desktop.
Save devstopfix/b397424e9b39396ca0abaf6b3b2c0707 to your computer and use it in GitHub Desktop.
Midpoint Circle Algorithm (Bresenham)
; https://en.wikipedia.org/wiki/Midpoint_circle_algorithm
(defn mirror-point [x0 y0 x y]
[[(+ x0 x) (+ y0 y)]
[(+ x0 y) (+ y0 x)]
[(- x0 y) (+ y0 x)]
[(- x0 x) (+ y0 y)]
[(- x0 x) (- y0 y)]
[(- x0 y) (- y0 x)]
[(+ x0 y) (- y0 x)]
[(+ x0 x) (- y0 y)]])
(defn circle [x0 y0 radius]
"Return a seq of [x y] points of a circle of given radius centred on [x0 y0]"
(loop [x radius, y 0, err 0, result []]
(if (>= x y)
(let [p (mirror-point x0 y0 x y)
y (inc y)
err (+ err (inc (* 2 y)))]
(if (pos? (inc (* 2 (- err x))))
(recur (dec x) y (+ err (- 1 (* 2 x))) (concat result p))
(recur x y err (concat result p))))
result)))
@devstopfix
Copy link
Author

devstopfix commented Aug 18, 2016

(->>
  (circle 0 0 200)
  (map #(let [[a b] %] (format "%d, %d" a b)))
  (clojure.string/join "\n")
  (spit "/tmp/circle-200.csv"))

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