Skip to content

Instantly share code, notes, and snippets.

@Pranz
Last active August 29, 2015 14:01
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 Pranz/45eff77d201ef1e2dc61 to your computer and use it in GitHub Desktop.
Save Pranz/45eff77d201ef1e2dc61 to your computer and use it in GitHub Desktop.
module Raining where
waterVolume :: [Int] -> Int
waterVolume xs = water 0 0 [] xs
where water maxHeight accWater puddles [] = accWater
water maxHeight accWater puddles (x:xs)
| x >= maxHeight = water x (accWater + sum (map (flip subtract maxHeight) puddles)) [] xs
| null puddles = water maxHeight accWater [x] xs
| x > head puddles = let (waterFilled, rest) = break (>= x) puddles in water maxHeight (accWater + sum (map (flip subtract x) waterFilled)) ((waterFilled >> return x) ++ rest) xs
| otherwise = water maxHeight accWater (x:puddles) xs
main :: IO ()
main = print . waterVolume $ [2,1,3,2,0,0,7,4,5,6,8,4,3,2,1,5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment