Skip to content

Instantly share code, notes, and snippets.

@pepe
Last active July 27, 2017 18:52
Show Gist options
  • Save pepe/706c107878847c7c3f6a30e473fb91c4 to your computer and use it in GitHub Desktop.
Save pepe/706c107878847c7c3f6a30e473fb91c4 to your computer and use it in GitHub Desktop.
(require '[clojure.zip :as zip])
(defn zzz [root] (zip/zipper vector? rest (fn [[x _ _] children] (vec (cons x children))) root))
(def tree ["Bea" ["Ales" ["Tom"] ["Atom" ["Elektron" ["Quark"] ["Bark"]] ["Proton"]]] ["Jarko" ["Letko"] ["Zimko" ["Prosko"] ["Ledko"]]]])
(defn normalize-tree [root lenght]
(loop [loc (zzz root) lookup {} result []]
(if (zip/end? loc)
result
(let [parent (zip/up loc)
pid (when parent (hash (zip/node parent)))
path (zip/path loc)
depth (count path)
branch (if parent (if (zip/left loc) :right :left) :root)
node (zip/node loc)
id (hash node)
label (first node)
[parx pary] (last (get-in lookup [(dec depth) pid]))
x ((if (= branch :left) - +) parx (/ lenght (Math/pow 2 (inc depth))))
y (* depth 10)]
(recur (zip/next loc)
(if label
(update lookup depth assoc id [pid branch label [parx pary] [x y]])
lookup)
(if label
(conj result [label [parx pary] [x y]])
result))))))
(normalize-tree tree 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment