Skip to content

Instantly share code, notes, and snippets.

@mzero
Created September 16, 2012 06:53
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 mzero/3731333 to your computer and use it in GitHub Desktop.
Save mzero/3731333 to your computer and use it in GitHub Desktop.
minimum path value through a triangle
module Triangle where
-- top-down version
minTriangleFlow :: (Num a, Ord a) => [[a]] -> a
minTriangleFlow = minimum . foldl sift []
where sift as bs = zipWith (+) bs $ pres as
pres [] = [0]
pres as@(ah:at) = ah : zipWith min as at ++ [last as]
-- bottom-up version (not safe if triangle input is misformed)
minTriangleFlow' :: (Num a, Ord a) => [[a]] -> a
minTriangleFlow' = minimum . foldr sift (repeat 0)
where sift as bs = zipWith (+) as $ zipWith min bs (tail bs)
exampleTriangle =
[ [1]
, [2 , 4]
, [5 , 1 , 4]
, [2 , 3 , 4 , 5]
]
main = print $ minTriangleFlow exampleTriangle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment