Skip to content

Instantly share code, notes, and snippets.

@mzdravkov
Created July 9, 2015 12:08
Show Gist options
  • Save mzdravkov/218b2a5b45db13718d04 to your computer and use it in GitHub Desktop.
Save mzdravkov/218b2a5b45db13718d04 to your computer and use it in GitHub Desktop.
(defn tree
[arr]
(if (empty? arr)
[]
[[(tree (rest arr))]
[(tree (reverse
(rest
(reverse arr))))]]))
(defn all-paths
([arr] (partition (dec (count arr))
(all-paths (tree arr) [])))
([tree path]
(if (empty? (last tree))
[]
(let [lpaths (all-paths (last (first tree)) (conj path :l))
rpaths (all-paths (last (second tree)) (conj path :r))
paths (concat lpaths rpaths)]
(if (empty? paths)
path
paths)))))
(defn evaluate
([arr] (let [paths (all-paths arr)]
(first
(sort-by second
>
(map #(vector % (evaluate % arr 1)) paths)))))
([path arr depth]
(if (empty? arr)
0
(let [curr (first path)
value (if (= curr :l)
(first arr)
(last arr))
path (rest path)
arr (if (= curr :l)
(rest arr)
(reverse (rest (reverse arr))))]
(+ (* depth value)
(evaluate path arr (inc depth)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment