From 6be1000993f739b59774f57797f2f2575695fd8c Mon Sep 17 00:00:00 2001 From: timofey Date: Tue, 30 May 2023 00:59:31 +0000 Subject: [PATCH] `avl` test --- src/flow/binary/avl.rs | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/flow/binary/avl.rs b/src/flow/binary/avl.rs index 8e9ea24..5a2d819 100644 --- a/src/flow/binary/avl.rs +++ b/src/flow/binary/avl.rs @@ -26,6 +26,14 @@ impl Display for AvlN { } } +#[cfg(test)] +impl AvlN { + fn balanced(&self) -> bool { + let (lh, rh) = (self.l.height, self.r.height); + std::cmp::max(lh, rh) - std::cmp::min(lh, rh) < 2 && self.l.balanced() && self.r.balanced() + } +} + struct AvlR { node: Rc>, } @@ -44,6 +52,13 @@ impl Display for AvlR { } } +#[cfg(test)] +impl AvlR { + fn balanced(&self) -> bool { + self.node.balanced() + } +} + struct AvlT { reference: Option>, height: u64, @@ -67,6 +82,16 @@ impl Display for AvlT { } } +#[cfg(test)] +impl AvlT { + fn balanced(&self) -> bool { + match &self.reference { + Some(reference) => reference.balanced(), + None => true, + } + } +} + struct AvlTs { _a: PhantomData, } @@ -170,3 +195,29 @@ impl<'a, A: 'a + PartialOrd> BinaryTreesAvl<'a> for AvlTs { AvlN { l: tl, r: tr, key } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + let trees = AvlTs::new(); + let mut tree = trees.empty(); + for i in [ + 8, 3, 10, 17, 0, 13, 6, 1, 11, 5, 4, 7, 18, 14, 15, 9, 2, 19, 16, 12, + ] { + tree = trees.clone().add_tree(tree, i.into()); + assert!(tree.balanced()); + // println!("{} {}", tree.height, tree); + } + for i in [ + 2, 9, 4, 7, 8, 10, 17, 1, 13, 15, 18, 12, 5, 0, 3, 6, 16, 19, 14, 11, + ] { + tree = trees.clone().remove(tree, i.into()); + assert!(tree.balanced()); + // println!("{} {}", tree.height, tree); + } + // assert!(false); + } +}