Pages

Monday, September 6, 2010

Euler Project Problem 81 with F#

module Problem81

let readfile fileName =
    let lines = System.IO.File.ReadAllLines(fileName)
    let data =
        let splitter = [|','|]
        lines
        |> Seq.map (fun line -> line.Split(splitter) |> Seq.map (fun element->float(element)))
    data

let m = Matrix.ofSeq (readfile @".\matrix.txt")

let cols = m.NumCols - 1
let rows = m.NumRows - 1

let tempMatrix = Matrix.create (cols+1) (rows+1) -1.

let rec f x y =
    let v = tempMatrix.[x,y]
    if (v <> -1.) then
        v
    else
        let getResult =
            let d = m.[x,y]
            match x,y with
                | (a,b) when a=cols && b=rows -> d
                | (a,_) when a=cols -> d + f x (y+1)
                | (_,b) when b=rows -> d + f (x+1) y
                | _ ->
                    let right = f (x+1) y
                    let down = f x (y+1)
                    d + (min right down)
        tempMatrix.[x,y] <- float(getResult)
        getResult

let solve = f 0 0

printfn "%A" solve

No comments: