From 7e00275e9ab4d2303b415d1f5a1baea1f38d2f6d Mon Sep 17 00:00:00 2001 From: harshey1103 <80175524+harshey1103@users.noreply.github.com> Date: Fri, 6 Oct 2023 02:33:23 +0530 Subject: [PATCH] Depth function (#22) --- src/rtree.ml | 10 ++++++++++ src/rtree_intf.ml | 3 +++ test/basic.ml | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/src/rtree.ml b/src/rtree.ml index 315e7ae..6391c7f 100644 --- a/src/rtree.ml +++ b/src/rtree.ml @@ -222,6 +222,16 @@ module Make (E : Envelope) (V : Value with type envelope = E.t) = struct let load ?(max_node_load = 8) entries = let tree = omt ~m:max_node_load entries in { max_node_load; tree } + + let rec depth' node depth = + match node with + | Node ns -> + let sub_depths = List.map (fun (_, n) -> depth' n depth + 1) ns in + List.fold_left max 0 sub_depths + | Leaf _ -> 1 + depth + | Empty -> depth + + let depth t = depth' t.tree 0 end module Rectangle = Rectangle diff --git a/src/rtree_intf.ml b/src/rtree_intf.ml index 05cd679..b6b327e 100644 --- a/src/rtree_intf.ml +++ b/src/rtree_intf.ml @@ -122,6 +122,9 @@ module type S = sig a better tree and is preferred over folding with {! insert}. It uses the {{: https://ceur-ws.org/Vol-74/files/FORUM_18.pdf} OMT algorithm}. *) + + val depth : t -> int + (** [depth tree] returns the depth of the tree. *) end module type Maker = functor diff --git a/test/basic.ml b/test/basic.ml index 860e5b5..58f14c4 100644 --- a/test/basic.ml +++ b/test/basic.ml @@ -158,6 +158,37 @@ let rectangle () = let r = Rtree.Rectangle.merge_many [ r1; r2 ] in assert (r = r3) +let test_depth () = + let module R = + Rtree.Make + (Rtree.Rectangle) + (struct + type t = line + + let t = lint_t + + type envelope = Rtree.Rectangle.t + + let envelope { p1 = x1, y1; p2 = x2, y2 } = + let x0 = Float.min x1 x2 in + let x1 = Float.max x1 x2 in + let y0 = Float.min y1 y2 in + let y1 = Float.max y1 y2 in + Rtree.Rectangle.v ~x0 ~y0 ~x1 ~y1 + end) + in + let lines = + [ + { p1 = (0., 0.); p2 = (1., 1.) }; + { p1 = (1., 1.); p2 = (2., 2.) }; + { p1 = (2., 2.); p2 = (3., 3.) }; + { p1 = (3., 3.); p2 = (4., 4.) }; + ] + in + let t = R.load ~max_node_load:2 lines in + let calc_depth = R.depth t in + assert (calc_depth = 2) + let suite = "R" >::: [ @@ -166,6 +197,7 @@ let suite = "lines" >:: test_lines; "omt" >:: omt_loader; "rect" >:: rectangle; + "depth" >:: test_depth; ] let _ = run_test_tt_main suite