Advertisement
Guest User

Untitled

a guest
Jan 14th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.93 KB | None | 0 0
  1. type node = Some of int | None
  2. type graph = (node * float * node ) list
  3.  
  4. let graph = [(0, 0.5, 1); (1, 0.2, 3); (1, 0.8, 4); (2, 0.4, 4)]
  5.  
  6. let nodes g = List.sort_uniq (fun a b-> if a=b then 0 else if a < b then -1 else 1)
  7.     (List.fold_left (fun out (a,b,c) -> a::c::out) [] g)
  8.  
  9. (*returns an assoc list with (node, (distanceToSource, predecessor)) predecessor = -1 if its not known*)
  10. let init source =
  11.   let n = nodes graph in
  12.   let dist_pred_list = List.fold_right (fun (x:int) out-> if x<>source then (infinity,None)::out else (0.0,None)::out) n [] in
  13.   List.combine n dist_pred_list
  14.  
  15. let rec run graph count infolist =
  16.   if count >= 0 then
  17.     List.fold_right (fun (u,w,v) out ->
  18.         let u_info = (List.assoc u infolist) in
  19.         let v_info = (List.assoc v infolist) in
  20.         if (fst u_info) +. w < fst v_info then
  21.         (v,((fst u_info) +. w,u))::out else out
  22.       ) graph [] in
  23.   run graph (count-1) infolist
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement