Advertisement
hoewarden

Untitled

Aug 14th, 2019
3,275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ; with reduce
  2. (defn trap-rain-water [h]
  3.   (let [max-pos (first (apply max-key second (map-indexed vector h)))
  4.         [left-h  right-h] (split-at max-pos h)
  5.         f (fn([[m v] x] (if (> x m) [x v] [m (+ v (- m x))])))]
  6.     (+ (second (reduce f [0 0] left-h))
  7.        (second (reduce f [0 0] (reverse right-h))))))
  8.  
  9. ; with loops
  10. (defn trap-rain-water [h]
  11.   (let [enumerated (map-indexed vector h)
  12.         max-pos (first (apply max-key second enumerated))]
  13.     (+ (loop [m 0 res 0 l enumerated]
  14.          (let [[pos x] (first l)]
  15.            (if (= pos max-pos)
  16.              res
  17.              (if (> x m)
  18.                (recur x res (rest l))
  19.                (recur m (+ res (- m x)) (rest l))))))
  20.        (loop [m 0 res 0 l (reverse enumerated)]
  21.          (let [[pos x] (first l)]
  22.            (if (= pos max-pos)
  23.              res
  24.              (if (> x m)
  25.                (recur x res (rest l))
  26.                (recur m (+ res (- m x)) (rest l)))))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement