Skip to content

Instantly share code, notes, and snippets.

@iokasimov
Created February 2, 2018 14:39
Show Gist options
  • Save iokasimov/60351d97af290f0e796b9a92aaefe30c to your computer and use it in GitHub Desktop.
Save iokasimov/60351d97af290f0e796b9a92aaefe30c to your computer and use it in GitHub Desktop.
Elegant solution for waterfall problem based on time traveling.
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