Skip to content

Instantly share code, notes, and snippets.

@mvarela
Created September 22, 2017 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvarela/ccc74615762658b48bb2370b73244800 to your computer and use it in GitHub Desktop.
Save mvarela/ccc74615762658b48bb2370b73244800 to your computer and use it in GitHub Desktop.
(ns fractals.core
( :require [hiccup.core :as hiccup]))
(def start [:F :X])
(defn rewrite [i]
(cond
(= :X i) [:X :+ :Y :F :+]
(= :Y i) [:- :F :X :- :Y]
:true [i]))
(defn dragon [segments iter]
(if (zero? iter)
segments
(let [segs (vec (mapcat rewrite segments))]
(recur segs (- iter 1)))))
(def pi:2 (/ Math/PI 2))
(def vec:size 3)
(defn points [segments theta acc x y]
(if (empty? segments)
acc
(let [s (first segments)
xs (rest segments)]
(cond
(or (= s :X) (= s :Y)) (recur xs, theta, acc, x, y)
(= s :+) (recur xs, (+ theta pi:2), acc, x, y)
(= s :-) (recur xs, (- theta pi:2), acc, x, y)
(= s :F) (let [xx (+ x (* vec:size (Math/cos theta)))
yy (+ y (* vec:size (Math/sin theta)))
new-acc (conj acc (vector xx yy))]
(recur xs, theta, new-acc, xx, yy))))))
(defn render-svg [plot-points]
(let [width 1800
height 1800
xmlns "http://www.w3.org/2000/svg"
style "stroke:#474674; fill:white;"
points (apply str (map #(str (first %) "," (second %) " ") plot-points))]
(hiccup/html [:svg {:width width
:height height
:xmlns xmlns}
[:polyline {:points points
:style style}]])))
(defn do-dragon[i]
(let [pts (points (dragon start i) 0 [] 800 600)]
(spit (str "dragon-" (if (< i 10) (str 0 i) i) ".svg") (render-svg pts))))
(map do-dragon (range 1 16))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment