Created
September 16, 2012 06:53
-
-
Save mzero/3731333 to your computer and use it in GitHub Desktop.
minimum path value through a triangle
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
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