Skip to content

Instantly share code, notes, and snippets.

@visibletrap
Created September 30, 2012 10:55
Show Gist options
  • Save visibletrap/3806453 to your computer and use it in GitHub Desktop.
Save visibletrap/3806453 to your computer and use it in GitHub Desktop.
Finding min path with brute force
(defn min-path [ivec]
(letfn [(expand [in]
(loop [n 0 acc [[0]]]
(if (= n in)
acc
(recur
(inc n)
(reduce
concat
(#(map (fn [n] [(cons 0 n) (cons 0 (map inc n))]) %) acc))))))]
(apply min (map
#(reduce + %)
(map
#(map (fn [[k v]] (nth (nth ivec k) v)) %)
(map #(zipmap (range) %) (expand (dec (count ivec))))))))
)
(= 7 (min-path '([1]
[2 4]
[5 1 4]
[2 3 4 5]))) ; 1->2->1->3
; true
(= 20 (min-path '([3]
[2 4]
[1 9 3]
[9 9 2 4]
[4 6 6 7 8]
[5 7 3 5 1 4]))) ; 3->4->3->2->7->1
; true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment