开发者

need help to read file with specific formatted contents

i'm using F#. I want to solve some problem that require me to read the input from a file, i don't know what to do. The first line in the file consist of three numbers, the first two numbers is the x and y for an map for the next line. The example file:

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

the meaning of 5 5 10 is the next line have 5x5 map and 10 is just some numbers that i need to solve the problem, the next until the end of the line is contents of the map that i have to solve using the 10 and i want to save this map numbers in 2 dimensional arr开发者_JAVA技巧ay. Someone can help me to write a code to save the all the numbers from the file so i can process it? * Sorry my english is bad, hope my question can be understood :)

The answer for my own question : Thanks for the answer from Daniel and Ankur. For my own purpose i mix code from both of you:

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

Many Thanks :D


Here's some quick and dirty code. It returns a tuple of the last number in the header (10 in this case) and a two-dimensional array of the values.

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"


In case the file is this much only (no further data to process) and always in correct format (no need to handle missing data etc) then it would be as simple as:

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
    |]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜