Created
September 16, 2012 00:21
-
-
Save dewitt/3730531 to your computer and use it in GitHub Desktop.
Triangle Minimal Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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