Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Project Euler problem 18/67 solver in Haskell

Name: Anonymous 2009-10-22 19:51


maximumPath :: [[Int]] -> Int
maximumPath tl = head $ foldl (flip reduce) (head rtl) (tail rtl)
  where rtl = reverse tl
        reduce [] b = []
        reduce a [] = []
        reduce (a:as) (b:c:bs) = (a + max b c) : reduce as (c:bs)
        reduce (a:as) [b] = [a + b]


To solve 67 (which is the more interesting one),


trif <- readFile "triangle.txt"
let answer = maximumPath $ map (\l -> map read l) (map words (lines trif))

Name: Anonymous 2009-10-22 23:22

>>5
Because I wrote reduce first, and then noticed that I had to flip the arguments if I wanted to do the folding, so I just put in a flip. You can just manually unflip it if you're so peeved by it.

I'm not sure what you mean by "large inputs", unless you mean interger overflow, in which case it could. If you change "Int" to "Integer", then this should work on any "numbers triangle" you give it.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List