Guest User

Untitled

a guest
Oct 16th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. type 'a Node = 'a * 'a list
  2. type 'a Graph = 'a Node list
  3. let g = [('a', ['b'; 'd']); ('b', ['a'; 'c'; 'd']); ('c', ['b']); ('d', ['a'; 'b']); ('e', ['f']); ('f', ['e'])]
  4.  
  5. let findConnectedGraph (map : Map<'a, 'a list>) (firstVal : 'a) =
  6. let rec walk (seen : 'a list) (tosearch : 'a list) =
  7. let isSeen n =
  8. seen |> List.exists (fun i -> i=n)
  9. let notSeenOnly (nodes : 'a list) =
  10. nodes |> List.filter (fun i -> not <| isSeen i)
  11.  
  12. let notSeenNeighbors = tosearch |> List.collect (fun i -> map.[i] |> notSeenOnly)
  13. match tosearch with
  14. | [] -> seen
  15. | _ -> walk (seen @ notSeenNeighbors) notSeenNeighbors
  16.  
  17. walk [firstVal] [firstVal]
  18.  
  19. let findAllConnectedGraphs (g : 'a Graph) =
  20. let map = Map.ofList g
  21. let rec findAllConnectedGraphsWorker (availableNodes : 'a list) = [
  22. let graph = findConnectedGraph map (availableNodes |> List.head)
  23. yield graph
  24. let remainingNodes = (Set.ofList availableNodes) - (Set.ofList graph)
  25. if not (Set.isEmpty remainingNodes) then
  26. yield! findAllConnectedGraphsWorker (Set.toList remainingNodes)
  27. ]
  28.  
  29. findAllConnectedGraphsWorker (g |> List.map (fun i -> fst i))
  30.  
  31. let result = findAllConnectedGraphs g
  32. printfn "RESULT: %A" result
Add Comment
Please, Sign In to add comment