Skip to content

Instantly share code, notes, and snippets.

@char16t
Last active April 5, 2019 12:55
Show Gist options
  • Save char16t/bb94c4113fa484847f555c6691d2b85f to your computer and use it in GitHub Desktop.
Save char16t/bb94c4113fa484847f555c6691d2b85f to your computer and use it in GitHub Desktop.
Simplest implementation of Voronoi diagram on Clojure
(ns voronoi-clojure.core
(:gen-class)
(:import (java.io File)
(javax.imageio ImageIO)
(java.awt.image BufferedImage)
(java.awt.geom Ellipse2D Ellipse2D$Double)
(java.awt Color)))
(defn- distance [x1 x2 y1 y2]
(Math/sqrt (+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2)))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(let [cells 20
size 1000
px (take cells (repeatedly #(rand-int size)))
py (take cells (repeatedly #(rand-int size)))
color (take cells (repeatedly #(rand-int 16777215)))
img (BufferedImage. size size BufferedImage/TYPE_INT_RGB)
gr (.createGraphics img)]
(with-local-vars [n 0]
(doseq [x (range size)
y (range size)
i (range cells)]
(do (cond (< (distance (nth px i) x (nth py i) y)
(distance (nth px (var-get n)) x (nth py (var-get n)) y))
(var-set n i))
(.setRGB img x y (int (nth color (var-get n)))))))
(.setColor gr (Color/BLACK))
(doseq [i (range cells)]
(.fill gr (Ellipse2D$Double. (nth px i) (nth py i) 5 5))
(ImageIO/write img "png" (File. "test.png")))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment