1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-18 14:44:48 +00:00
janet/examples/maxtriangle.dst
2018-03-25 21:12:43 -04:00

43 lines
756 B
Plaintext

# Find the maximum path from the top (root)
# of the triangle to the leaves of the triangle.
(defn vmap2 [f m1 m2]
(def len (length m1))
(def arr @[])
(for [i 0 len] (array-push arr (f (get m1 i) (get m2 i))))
arr)
(defn reduce [s f c]
(var res s)
(for [i 0 (length c)]
(:= res (f res (get c i))))
res)
(defn max1 [l r] (if (< l r) r l))
(defn myfold [xs ys]
(def xs1 (tuple-prepend xs 0))
(def xs2 (tuple-append xs 0))
(def m1 (vmap2 + xs1 ys))
(def m2 (vmap2 + xs2 ys))
(vmap2 max1 m1 m2))
(defn max [a]
(var m (get a 0))
(for [i 0 (length a)]
(if (< m (get a i))
(:= m (get a i))))
m)
(defn maxpath [t]
(max (reduce () myfold t)))
(def triangle @[
@[3]
@[7 10]
@[4 3 7]
@[8 9 1 3]
])
(print (maxpath triangle))