2011-09-28 65 views
2

我正在使用F#。我想解決一些需要我從文件中讀取輸入的問題,我不知道該怎麼做。文件中的第一行由三個數字組成,前兩個數字是下一行的映射的x和y。示例文件:需要幫助閱讀具有特定格式化內容的文件

5 5 10 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

的5 5 10的意思是下一行有5×5的地圖和10僅僅是一些數字,我需要解決的問題,下到行到底是內容地圖,我必須解決使用10,我想保存在2維數組這個地圖數字。有人可以幫我寫一段代碼來保存文件中的所有數字,以便我可以處理它? *對不起,我的英語不好,希望我的問題可以理解:)

我自己的問題的答案: 感謝Daniel和Ankur的回答。對於我自己的目的,我從你們兩個混代碼:

let readMap2 (path:string) = 
    let lines = File.ReadAllLines path 
    let [|x; y; n|] = lines.[0].Split() |> Array.map int 
    let data = 
     [| 
      for l in (lines |> Array.toSeq |> Seq.skip 1) do 
       yield l.Split() |> Array.map int 
     |] 
    x,y,n,data 

非常感謝:d

回答

1

下面是一些快速和骯髒的代碼。它返回標題中最後一個數字的元組(本例中爲10)和值的二維數組。

open System.IO 

let readMap (path:string) = 
    use reader = new StreamReader(path) 
    match reader.ReadLine() with 
    | null -> failwith "empty file" 
    | line -> 
    match line.Split() with 
    | [|_; _; _|] as hdr -> 
     let [|x; y; n|] = hdr |> Array.map int 
     let vals = Array2D.zeroCreate y x 
     for i in 0..(y-1) do 
     match reader.ReadLine() with 
     | null -> failwith "unexpected end of file" 
     | line -> 
      let arr = line.Split() |> Array.map int 
      if arr.Length <> x then failwith "wrong number of fields" 
      else for j in 0..(x-1) do vals.[i, j] <- arr.[j] 
     n, vals 
    | _ -> failwith "bad header" 
+0

啊,是的,謝謝你,對不起,我忘了一些東西,我想保存在2維數組中的地圖內容,你能幫我 –

+0

我用鋸齒陣列,因爲它們表現更好,但我更新它使用二維。 – Daniel

0

如果該文件是這麼多隻(沒有進一步的數據處理),並始終在正確的格式(無需處理丟失數據等),那麼這將是這麼簡單:

let readMap (path:string) = 
    let lines = File.ReadAllLines path 
    let [|_; _; n|] = lines.[0].Split() |> Array.map int 
    [| 
     for l in (lines |> Array.toSeq |> Seq.skip 1) do 
      yield l.Split() |> Array.map int 
    |]