Skip to content

Instantly share code, notes, and snippets.

@dewitt
Created September 16, 2012 00:21
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 dewitt/3730531 to your computer and use it in GitHub Desktop.
Save dewitt/3730531 to your computer and use it in GitHub Desktop.
Triangle Minimal Path
(fn min-path- [triangle]
^{:doc "79. Write a function which calculates the sum of the minimal
path through a triangle."}
;; We're going to use a dynamic programming solution, which will
;; reduce from the bottom of the triangle upward, replacing each row
;; with the sum from there on down. After the final reduction the
;; single remaining row will contain one element with the sum of the
;; min path.
(loop [r (reverse triangle)]
(if (= 1 (count r))
(ffirst r)
(recur (cons
(map min
(map + (second r) (butlast (first r)))
(map + (second r) (rest (first r))))
(drop 2 r))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment