Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rdsr
Created November 16, 2010 05:20
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 rdsr/701475 to your computer and use it in GitHub Desktop.
Save rdsr/701475 to your computer and use it in GitHub Desktop.
(use '[clojure.contrib.duck-streams :only (reader read-lines)])
(defn build-sum-mtx [triangle]
(let [len (count triangle)]
(loop [mtx [] i 0]
(cond
(= i len) mtx
:else (let [row (get mtx (dec i))
sum (fn [n j]
(let [a (or (get row (dec j)) 0)
b (or (get row j) 0)]
(+ (max a b) n)))]
(recur (conj mtx
;; converting back lazyseq from map to a vector
;; since we would access it (on line 8) in the next iteration
(vec (map sum (get triangle i) (range 0 (inc i)))))
(inc i)))))))
(defn max-sum [mtx] (apply max (last mtx)))
(defn problem-67 []
(max-sum
(build-sum-mtx
;; reduce below builds a triangle as a vector of vectors
(reduce
conj []
(map (fn [line]
(vec (map #(Integer. %)
(.split line " "))))
(read-lines (reader "http://projecteuler.net/project/triangle.txt")))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment