Created
February 2, 2018 14:39
-
-
Save iokasimov/60351d97af290f0e796b9a92aaefe30c to your computer and use it in GitHub Desktop.
Elegant solution for waterfall problem based on time traveling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad.Tardis | |
import Data.Traversable | |
water :: Traversable t => t Int -> Int | |
water = foldr (+) 0 . flip evalTardis (0, 0) . traverse (go 0) where | |
go :: Int -> Int -> Tardis Int Int Int | |
go total height = do | |
modifyForwards $ max height | |
(leftmax, rightmax) <- (,) <$> getPast <*> getFuture | |
modifyBackwards $ max height | |
return $ total + min leftmax rightmax - height | |
main = print $ water [2,5,1,2,3,4,7,7,6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment