September 7, 2018
Just Juxt #24: Triangle Minimal Path (4clojure #79)
Write a function which calculates the sum of the minimal path through a triangle. The triangle is represented as a collection of vectors. The path should start at the top of the triangle and move to an adjacent number on the next row until the bottom of the triangle is reached.
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn tri-path [[[top] & rem]]
(letfn [(left-tri [tri] (map butlast tri))
(right-tri [tri] (map rest tri))]
(if (seq rem)
(->> rem
((juxt left-tri right-tri))
(map tri-path)
(apply min)
(+ top))
top)))
(deftest test-79
(is (= (tri-path [[1] [2 4] [5 1 4] [2 3 4 5]]) (+ 1 2 1 3) 7))
(is (= (tri-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) 20)))
(run-tests)