Guest User

Untitled

a guest
Feb 25th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.07 KB | None | 0 0
  1. //http://www.reddit.com/r/dailyprogrammer/comments/2uo3yf/20150204_challenge_200_intermediate_metro_tile/
  2. type point = {x:int;y:int}
  3. type tile = {position : point; width : int; height : int}
  4. let width, height = (fun (s : string array) -> (int(s.[0]), int(s.[1]))) (System.Console.ReadLine().Split(' '))
  5. let boardchrs = ([for i in 1 .. height do yield System.Console.ReadLine()] |> List.fold (fun str line -> str + line) "").ToCharArray()
  6. let board = Array2D.create height width ('.')
  7. for x in 0..height - 1 do
  8.     for y in 0..width - 1 do
  9.         Array2D.set board x y (boardchrs.[x*width + y])
  10.  
  11. let rec checktiles pos tiles =
  12.     match tiles with
  13.     | h :: t -> if (h.position.x <= pos.x && pos.x <= h.position.x + h.width - 1) && (h.position.y <= pos.y && pos.y <= h.position.y + h.height - 1) then true else checktiles pos t
  14.     | _ -> false
  15.  
  16. let incpos (pos : point) =
  17.     match pos with
  18.     | {x = x; y = y} when y = height - 1 && x = width - 1 -> pos
  19.     | {x = x; y = y} when y < height - 1 -> {pos with y = y + 1}
  20.     | {x = x; y = y} when y = height - 1 -> {x = x + 1; y = 0}
  21.     | _ -> printfn "This should never happen"; pos
  22.  
  23. let findtile pos =
  24.     let rec findwidth pos currwidth =
  25.         if pos.x = width then currwidth
  26.         elif board.[pos.y, pos.x] <> '.' then findwidth {pos with x = pos.x + 1} (currwidth + 1)
  27.         else currwidth
  28.     let rec findheight pos currheight =
  29.         if pos.y = height then currheight
  30.         elif board.[pos.y, pos.x] <> '.' then findheight {pos with y = pos.y + 1} (currheight + 1)
  31.         else currheight
  32.     {position = pos; width = findwidth pos 0; height = findheight pos 0}
  33.  
  34. let rec scanboard pos tiles =
  35.     if board.[pos.y, pos.x] <> '.' && not(checktiles pos tiles) then scanboard (incpos pos) ((findtile pos) :: tiles)
  36.     elif incpos pos <> pos then scanboard (incpos pos) tiles
  37.     else tiles
  38.  
  39. let tiles = scanboard {x = 0; y = 0} []
  40. tiles |> List.rev |> List.iter (fun t -> printfn "%dx%d tile of character '%c' located at (%d,%d)" t.width t.height board.[t.position.y, t.position.x] t.position.x t.position.y)
Add Comment
Please, Sign In to add comment