Guest User

Untitled

a guest
Jun 18th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. module GumimazeAgent
  2. open Microsoft.FSharp.Control
  3. open System.Threading.Tasks
  4.  
  5. type ReducerMessage = Point of int | End
  6. type CounterMessage = Inc | Dec
  7. type WalkerMessage = Map<int*int, char> * (int * int) * Map<int*int, bool> * int;
  8.  
  9. let answer = new TaskCompletionSource<int>()
  10.  
  11. let reducer = MailboxProcessor<_>.Start(fun mb ->
  12. let rec mainLoop max = async {
  13. let! message = mb.Receive()
  14. match message with
  15. | Point pt -> return! mainLoop (if pt > max then pt else max)
  16. | _ -> return answer.SetResult(max)
  17. }
  18. mainLoop 0
  19. )
  20.  
  21. let counter = MailboxProcessor<_>.Start(fun mb ->
  22. let rec mainLoop count = async {
  23. let! message = mb.Receive()
  24. let count =
  25. match message with
  26. | Inc -> count + 1
  27. | Dec -> count - 1
  28. if count > 0 then
  29. return! mainLoop count
  30. else
  31. End |> reducer.Post(ReducerMessage.End)
  32. }
  33. mainLoop 0
  34. )
  35.  
  36. let rec walkerBody = fun (mb: MailboxProcessor<_>) -> async {
  37. let! msg = mb.Receive()
  38. let walked = Map.add msg.Position true msg.Walked
  39. let aroundP =
  40. let x, y = msg.Position
  41. [x+1, y; x, y+1; x-1, y; x, y-1]
  42. for p in aroundP do
  43. match Map.containsKey p walked, Map.find p msg.Maze with
  44. | true, _ -> ()
  45. | _ , 'W' -> ()
  46. | _ , '1' ->
  47. Inc |> counter.Post
  48. let walker = MailboxProcessor<_>.Start(walkerBody)
  49. (msg.Maze, p, walked, msg.Point + 1) |> walker.Post
  50. | _ , 'G' ->
  51. Point msg.Point |> reducer.Post
  52. | _ , _ ->
  53. Inc |> counter.Post
  54. let walker = MailboxProcessor<_>.Start(walkerBody)
  55. (msg.Maze, p, walked, msg.Point) |> walker.Post
  56. Dec |> counter.Post
  57. }
  58. let walker = MailboxProcessor<_>.Start(walkerBody)
  59.  
  60. let withIndex xs =
  61. Array.mapi (fun i x -> x, i) xs
  62.  
  63. let read =
  64. let lines = "maze.txt" |> System.IO.File.ReadAllLines
  65. seq {
  66. for line, y in withIndex lines do
  67. for c, x in withIndex (line.ToCharArray ()) ->
  68. (x, y), c
  69. }
  70. |> Map.ofSeq
  71.  
  72. let solve maze =
  73. let p = maze |> Map.pick (fun k v -> if v = 'S' then Some k else None)
  74. Inc |> counter.Post
  75. (maze, p, Map.empty, 0) |> walker.Post
  76.  
  77. [<EntryPoint>]
  78. let main argv =
  79. read |> solve
  80. answer.Task.Result |> printfn "%A"
  81. 0
Add Comment
Please, Sign In to add comment