Skip to content

Instantly share code, notes, and snippets.

@danidiaz
Last active December 28, 2015 14:59
Show Gist options
  • Select an option

  • Save danidiaz/7518431 to your computer and use it in GitHub Desktop.

Select an option

Save danidiaz/7518431 to your computer and use it in GitHub Desktop.
My solution to the Twitter waterflow problem. Other solutions here: http://chrisdone.com/posts/twitter-problem-loeb
puddles :: [Int] -> Int
puddles l = go 0 [] (zip l (repeat 1)) where
go acc [] (a:b:xs)
| fst a <= fst b = go acc [] (b:xs)
| otherwise = go acc [a] (b:xs)
go acc (p@(pp,cp):ps) (a@(aa,ca):b@(bb,cb):xs)
| aa == bb = go acc (p:ps) ((aa,ca+cb):xs)
| aa < bb = let acc' = acc + ca * min (pp-aa) (bb-aa) in
if pp > bb
then go acc' (p:ps) ((bb,cb+ca):xs)
else go acc' ps ((pp,cp+ca):b:xs)
| otherwise = go acc (a:p:ps) (b:xs)
go acc _ _ = acc
main :: IO ()
main = do
putStrLn . show $ puddles $ [0,4,6,3]
putStrLn . show $ puddles $ [0,1,0,1]
putStrLn . show $ puddles $ [0,2,0,2]
putStrLn . show $ puddles $ [0,2,0,2,0,1]
putStrLn . show $ puddles $ [0,2,0,0,2,0,1]
putStrLn . show $ puddles $ [0,2,0,1,4,0,1]
putStrLn . show $ puddles $ [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