Advertisement
ptrelford

Minesweeper Kata

May 23rd, 2012
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.45 KB | None | 0 0
  1. let input = "4 4
  2. *...
  3. ....
  4. .*..
  5. ...."
  6.  
  7. let parseLines (lines:string[]) = [
  8.     let i = ref 0
  9.     while !i < lines.Length do
  10.         let header = lines.[!i]
  11.         let n, m =
  12.             match header.Split(' ') with
  13.             | [|n;m|] -> int n, int m
  14.             | _ -> failwith "Failed to parse header"
  15.         yield n,m,
  16.             [for y = 1 to n do
  17.                 let line = lines.[!i+y]
  18.                 yield [for c in line -> c]            
  19.             ]
  20.         i := !i + n + 1
  21.     ]
  22.  
  23. let parse (s:string) =    
  24.     let options = System.StringSplitOptions.RemoveEmptyEntries
  25.     let lines = s.Split([|'\r';'\n'|], options)
  26.     parseLines lines
  27.    
  28. let value c =
  29.     match c with
  30.     | '*' -> 1
  31.     | '.' -> 0
  32.     | _ -> failwith "Unexpected value"
  33.  
  34. let compute n m (board:char list list) =
  35.     let count (x,y) =
  36.         [-1,-1; 0,-1; 1,-1
  37.          -1, 0;       1, 0
  38.          -1, 1; 0, 1; 1, 1]
  39.         |> List.sumBy (fun (dx,dy) ->
  40.             let x, y = x + dx, y + dy
  41.             if y>=0 && y<n && x>=0 && x<m
  42.             then board.[y].[x] |> value
  43.             else 0
  44.         )
  45.     board |> List.mapi (fun y line ->
  46.         line |> List.mapi (fun x c ->        
  47.             match c with
  48.             | '*' -> c
  49.             | '.' -> '0' + char (count(x,y))
  50.             | _ -> failwith "Unexpected value"  
  51.         )
  52.     )
  53.  
  54. let boards = parse input
  55. let n,m,board = boards |> List.head
  56. let result = compute n m board
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement