75using ::testing::AssertionFailure;
76using ::testing::AssertionResult;
77using ::testing::AssertionSuccess;
96 std::ostringstream
out;
98 for (
size_t i = 0; i <
keys.size(); ++i)
99 out << (i == 0 ?
"" :
", ") <<
keys[i];
105 size_t min_avl_nodes(
const int h)
noexcept
107 size_t below = 0, at = 1;
110 for (
int i = 1; i <
h; ++i)
112 const size_t next = at + below + 1;
120 template <
class Tree>
127 std::optional<Tree> tree;
128 std::multiset<int> model;
129 std::vector<std::unique_ptr<Node>>
nodes;
130 std::vector<Node *> spare;
131 std::vector<int>
keys;
134 Node * take_node(
const int key)
138 nodes.push_back(std::make_unique<Node>(key));
139 return nodes.back().get();
142 Node * p = spare.back();
149 void walk(
Node * p,
const int depth)
151 if (p == Node::NullPtr)
155 walk(
LLINK(p), depth + 1);
157 walk(
RLINK(p), depth + 1);
160 AssertionResult check_ranks()
162 if constexpr (Ranked_Tree<Tree>)
165 for (
const int key : model)
167 Node * p = tree->select(i);
168 if (p ==
nullptr or p == Node::NullPtr or
KEY(p) != key)
169 return AssertionFailure() <<
"select(" << i <<
") is not the node of key " << key;
171 const auto [pos, q] = tree->position(key);
172 if (pos < 0 or
static_cast<size_t>(pos) >=
keys.size() or keys[pos] != key)
173 return AssertionFailure() <<
"position(" << key <<
") is " << pos;
174 if (q ==
nullptr or q == Node::NullPtr or
KEY(q) != key)
175 return AssertionFailure() <<
"position(" << key <<
") did not give its node";
179 const int absent = model.empty() ? 0 : *model.rbegin() + 1;
180 if (tree->position(absent).first != -1)
181 return AssertionFailure() <<
"position() of the absent key " << absent <<
" is not -1";
184 return AssertionSuccess();
188 explicit Checked_Tree(
const unsigned long seed = 1) { restart(
seed); }
191 void restart([[maybe_unused]]
const unsigned long seed)
194 for (
auto & p :
nodes)
195 spare.push_back(p.get());
198 if constexpr (Seeded_Tree<Tree>)
199 tree->set_seed(
seed);
202 [[nodiscard]]
size_t size() const noexcept {
return model.size(); }
204 [[nodiscard]]
bool has(
const int key)
const {
return model.count(key) > 0; }
206 [[nodiscard]]
const std::multiset<int> &
expected() const noexcept {
return model; }
209 [[nodiscard]] std::string signature()
212 write_signature(tree->getRoot(),
out);
216 AssertionResult
insert(
const int key)
218 const bool is_new = not has(key);
219 Node * p = take_node(key);
220 Node * q = tree->insert(p);
226 return AssertionFailure() <<
"insert(" << key <<
") accepted a key that was in the tree";
227 return AssertionSuccess();
231 return AssertionFailure() <<
"insert(" << key <<
") did not return the node of the new key";
233 return AssertionSuccess();
237 AssertionResult search_or_insert(
const int key)
239 const bool is_new = not has(key);
240 Node * p = take_node(key);
241 Node * q = tree->search_or_insert(p);
247 return AssertionFailure() <<
"search_or_insert(" << key
248 <<
") inserted a key that was in the tree";
249 if (q ==
nullptr or q == Node::NullPtr or
KEY(q) != key)
250 return AssertionFailure() <<
"search_or_insert(" << key
251 <<
") did not return the node that holds the key";
252 return AssertionSuccess();
256 return AssertionFailure() <<
"search_or_insert(" << key
257 <<
") did not return the node of the new key";
259 return AssertionSuccess();
262 AssertionResult insert_dup(
const int key)
264 Node * p = take_node(key);
265 if (tree->insert_dup(p) != p)
266 return AssertionFailure() <<
"insert_dup(" << key <<
") did not return the node inserted";
268 return AssertionSuccess();
271 AssertionResult
remove(
const int key)
273 const auto it = model.find(key);
274 Node * p = tree->remove(key);
276 if (it == model.end())
279 return AssertionFailure() <<
"remove(" << key <<
") gave a node for an absent key";
280 return AssertionSuccess();
283 if (p ==
nullptr or p == Node::NullPtr)
284 return AssertionFailure() <<
"remove(" << key <<
") did not find a key of the tree";
286 return AssertionFailure() <<
"remove(" << key <<
") gave the node of key " <<
KEY(p);
290 return AssertionSuccess();
295 AssertionResult remove_pos(
const size_t i)
297 if constexpr (Removes_By_Position<Tree>)
299 const auto it = std::next(model.begin(),
static_cast<std::ptrdiff_t
>(i));
300 Node * p = tree->remove_pos(i);
302 if (p ==
nullptr or p == Node::NullPtr)
303 return AssertionFailure() <<
"remove_pos(" << i <<
") gave no node";
305 return AssertionFailure() <<
"remove_pos(" << i <<
") gave the node of key " <<
KEY(p)
306 <<
" and the key there is " << *it;
310 return AssertionSuccess();
313 return AssertionFailure() <<
"the tree has no remove_pos(" << i <<
")";
316 AssertionResult
search(
const int key)
318 Node * p = tree->search(key);
323 return AssertionFailure() <<
"search(" << key <<
") gave a node for an absent key";
324 return AssertionSuccess();
327 if (p ==
nullptr or p == Node::NullPtr or
KEY(p) != key)
328 return AssertionFailure() <<
"search(" << key <<
") did not find a key of the tree";
329 return AssertionSuccess();
333 AssertionResult
check()
337 if (not tree->verify())
338 return AssertionFailure() <<
"verify() is false";
343 if (
keys.size() != model.size() or not std::equal(
keys.begin(),
keys.end(), model.begin()))
344 return AssertionFailure() <<
"the tree holds " <<
to_string(keys) <<
" and it must hold "
345 <<
to_string(std::vector<int>(model.begin(), model.end()));
347 if constexpr (Sized_Tree<Tree>)
348 if (tree->size() != model.size())
349 return AssertionFailure() <<
"size() is " << tree->size() <<
" with " << model.size()
352 if constexpr (Avl_Balanced_Node<Node>)
353 if (
keys.size() < min_avl_nodes(height))
354 return AssertionFailure() <<
"height " << height <<
" is too much for an AVL tree of "
355 <<
keys.size() <<
" nodes";
357 if constexpr (Colored_Node<Node>)
363 if (
keys.size() + 1 < (size_t(1) << (height / 2)))
364 return AssertionFailure() <<
"height " << height
365 <<
" is too much for a red-black tree of " <<
keys.size()
369 return AssertionSuccess();
375 AssertionResult deep_check()
377 if (
auto ok =
check(); not ok)
380 if (not model.empty())
381 if (
auto ok =
search(*model.begin() - 1); not ok)
384 for (
auto it = model.begin(); it != model.end(); it = model.upper_bound(*it))
386 if (
auto ok =
search(*it); not ok)
388 if (not has(*it + 1))
389 if (
auto ok =
search(*it + 1); not ok)
393 if (
auto ok = check_ranks(); not ok)
400 static void write_signature(
Node * p, std::string &
out)
402 if (p == Node::NullPtr)
408 out += std::to_string(
KEY(p));
409 if constexpr (Colored_Node<Node>)
411 if constexpr (Avl_Balanced_Node<Node>)
412 out +=
DIFF(p) < 0 ?
'-' :
DIFF(p) > 0 ?
'+' :
'=';
422 enum class Checks { invariants, searches_too };
424 template <
class Tree>
425 AssertionResult checked(Checked_Tree<Tree> & tree,
const Checks checks)
427 return checks == Checks::searches_too ? tree.deep_check() : tree.check();
431 template <
class Tree>
432 AssertionResult insert_all(Checked_Tree<Tree> & tree,
const std::vector<int> & order,
435 for (
const int key : order)
437 if (
auto ok = tree.insert(key); not ok)
439 if (
auto ok = checked(tree, checks); not ok)
440 return ok <<
" after inserting " << key;
442 return AssertionSuccess();
447 template <
class Tree>
448 AssertionResult remove_all(Checked_Tree<Tree> & tree,
const std::vector<int> & order,
451 for (
const int key : order)
453 if (
auto ok = tree.remove(key); not ok)
455 if (
auto ok = checked(tree, checks); not ok)
456 return ok <<
" after removing " << key;
459 if (
auto ok = tree.remove(key); not ok)
460 return ok <<
" the second time";
461 if (
auto ok = tree.check(); not ok)
462 return ok <<
" after removing " << key <<
" again";
464 return AssertionSuccess();
469 std::vector<std::pair<std::string, std::vector<int>>> adverse_orders(
const int n)
471 std::vector<int> ascending(n);
472 std::iota(ascending.begin(), ascending.end(), 1);
474 std::vector<int> descending(ascending.rbegin(), ascending.rend());
476 std::vector<int> from_both_ends;
477 for (
int lo = 1, hi = n; lo <= hi; ++lo, --hi)
479 from_both_ends.push_back(lo);
481 from_both_ends.push_back(hi);
485 std::vector<int> from_the_middle(from_both_ends.rbegin(), from_both_ends.rend());
487 std::vector<int> by_halves;
491 std::vector<bool> used(n + 1,
false);
492 for (
int step = top; step >= 1; step /= 2)
493 for (
int key = step; key <= n; key += step)
497 by_halves.push_back(key);
500 std::vector<int> shuffled(ascending);
501 std::mt19937
rng(20260710);
502 for (
size_t i = shuffled.size(); i > 1; --i)
503 std::swap(shuffled[i - 1], shuffled[
rng() % i]);
506 {
"ascending", ascending},
507 {
"descending", descending},
508 {
"from both ends", from_both_ends},
509 {
"from the middle", from_the_middle},
510 {
"by halves", by_halves},
511 {
"shuffled", shuffled}};
514 template <
class Tree>
515 class SearchTreeBattery :
public ::testing::Test
518 Checked_Tree<Tree> tree;
523 template <
class Tree>
524 class RankedTreeBattery :
public ::testing::Test {};
528 template <
class Tree>
529 class PositionalRemovalBattery :
public ::testing::Test
532 Checked_Tree<Tree> tree;
536 using Positional_Trees =
546TYPED_TEST(SearchTreeBattery, EveryInsertionOrderOfUpToEightKeys)
548 auto & tree = this->tree;
549 unsigned long sequences = 0;
551 for (
int n = 1; n <= 8; ++n)
553 std::vector<int> order(n);
554 std::iota(order.begin(), order.end(), 1);
558 tree.restart(++sequences);
559 ASSERT_TRUE(insert_all(tree, order, Checks::invariants))
561 ASSERT_TRUE(tree.deep_check()) <<
"after inserting " <<
to_string(order);
564 ASSERT_TRUE(tree.insert(order.front())) <<
"after " <<
to_string(order);
565 ASSERT_TRUE(tree.insert(order.back())) <<
"after " <<
to_string(order);
566 ASSERT_TRUE(tree.check()) <<
"after " <<
to_string(order);
568 while (std::next_permutation(order.begin(), order.end()));
571 EXPECT_EQ(sequences, 46233ul);
576TYPED_TEST(SearchTreeBattery, EveryOrderOfSearchOrInsertOfUpToSevenKeys)
578 auto & tree = this->tree;
579 unsigned long sequences = 0;
581 for (
int n = 1; n <= 7; ++n)
583 std::vector<int> order(n);
584 std::iota(order.begin(), order.end(), 1);
588 tree.restart(++sequences);
589 for (
const int key : order)
591 ASSERT_TRUE(tree.search_or_insert(key)) <<
"inserting " <<
to_string(order);
592 ASSERT_TRUE(tree.check())
593 <<
"after inserting " << key <<
" of " <<
to_string(order);
595 ASSERT_TRUE(tree.deep_check()) <<
"after inserting " <<
to_string(order);
598 ASSERT_TRUE(tree.search_or_insert(order.front())) <<
"after " <<
to_string(order);
599 ASSERT_TRUE(tree.search_or_insert(order.back())) <<
"after " <<
to_string(order);
600 ASSERT_TRUE(tree.check()) <<
"after " <<
to_string(order);
602 while (std::next_permutation(order.begin(), order.end()));
605 EXPECT_EQ(sequences, 5913ul);
608TYPED_TEST(SearchTreeBattery, EveryRemovalOrderFromEveryTreeOfUpToSixKeys)
610 auto & tree = this->tree;
611 unsigned long seed = 0;
614 for (
int n = 1; n <= 6; ++n)
616 std::set<std::string> seen;
617 std::vector<int> insertion(n);
618 std::iota(insertion.begin(), insertion.end(), 1);
623 tree.restart(++
seed);
624 for (
const int key : insertion)
625 ASSERT_TRUE(tree.insert(key));
626 if (not seen.insert(tree.signature()).second)
629 std::vector<int> removal(n);
630 std::iota(removal.begin(), removal.end(), 1);
634 for (
const int key : insertion)
635 ASSERT_TRUE(tree.insert(key));
637 ASSERT_TRUE(remove_all(tree, removal, Checks::invariants))
638 <<
"after inserting " <<
to_string(insertion) <<
", removing "
640 ASSERT_EQ(tree.size(), 0u);
642 while (std::next_permutation(removal.begin(), removal.end()));
644 while (std::next_permutation(insertion.begin(), insertion.end()));
646 shapes += seen.size();
649 EXPECT_GE(shapes, 6u);
650 this->RecordProperty(
"trees",
static_cast<int>(shapes));
653TYPED_TEST(SearchTreeBattery, EveryRemovalOrderOfSevenKeysFromGivenTrees)
655 auto & tree = this->tree;
657 unsigned long seed = 0;
659 for (
const auto & [name, insertion] : adverse_orders(n))
661 std::vector<int> removal(n);
662 std::iota(removal.begin(), removal.end(), 1);
665 tree.restart(++
seed);
666 for (
const int key : insertion)
667 ASSERT_TRUE(tree.insert(key));
669 ASSERT_TRUE(remove_all(tree, removal, Checks::invariants))
670 <<
"after inserting " <<
to_string(insertion) <<
" (" << name <<
"), removing "
673 while (std::next_permutation(removal.begin(), removal.end()));
686 template <
class Tree>
687 AssertionResult random_operations(Checked_Tree<Tree> & tree,
const unsigned seed,
688 const int universe,
const int num_ops,
689 const bool repeated_keys)
694 for (
int i = 0; i < num_ops; ++i)
696 const int key =
static_cast<int>(
rng() % universe);
697 const unsigned dice =
rng() % 100;
698 const unsigned inserts = i < num_ops / 3 ? 60 : i < 2 * num_ops / 3 ? 40 : 20;
700 AssertionResult done = AssertionSuccess();
701 const char * what =
"searching";
705 const unsigned how =
rng() % 4;
706 done = repeated_keys
and how < 2 ? tree.insert_dup(key) :
707 how == 3 ? tree.search_or_insert(key) : tree.insert(key);
712 if (Removes_By_Position<Tree>
and tree.size() > 0
and rng() % 4 == 0)
714 what =
"removing the key at position";
715 done = tree.remove_pos(key % tree.size());
718 done = tree.remove(key);
721 done = tree.search(key);
724 return done <<
" (operation " << i <<
", seed " <<
seed <<
")";
726 if (
auto ok = i % 61 == 0 ? tree.deep_check() : tree.
check(); not ok)
727 return ok <<
" after " << what <<
' ' << key <<
" (operation " << i <<
", seed "
731 std::vector<int> rest(tree.expected().begin(), tree.expected().end());
732 for (
size_t i = rest.size(); i > 1; --i)
733 std::swap(rest[i - 1], rest[
rng() % i]);
735 for (
const int key : rest)
737 if (
auto ok = tree.remove(key); not ok)
738 return ok <<
" (emptying, seed " <<
seed <<
")";
739 if (
auto ok = tree.check(); not ok)
740 return ok <<
" after removing " << key <<
" (emptying, seed " <<
seed <<
")";
743 if (tree.size() != 0)
744 return AssertionFailure() <<
"the tree was not emptied";
745 return tree.deep_check();
752 for (
const unsigned seed : {1u, 2u, 3u, 4u})
753 ASSERT_TRUE(random_operations(this->tree,
seed, 24, 6000,
false));
758 for (
const unsigned seed : {11u, 12u})
759 ASSERT_TRUE(random_operations(this->tree,
seed, 400, 5000,
false));
760 ASSERT_TRUE(random_operations(this->tree, 13u, 100000, 2500,
false));
763TYPED_TEST(SearchTreeBattery, RandomOperationsWithRepeatedKeys)
765 for (
const unsigned seed : {21u, 22u})
766 ASSERT_TRUE(random_operations(this->tree,
seed, 12, 4000,
true));
767 ASSERT_TRUE(random_operations(this->tree, 23u, 300, 4000,
true));
774TYPED_TEST(SearchTreeBattery, AdverseInsertionAndRemovalOrders)
776 auto & tree = this->tree;
777 const auto orders = adverse_orders(96);
778 unsigned long seed = 0;
780 for (
const auto & [inserting, insertion] : orders)
781 for (
const auto & [removing, removal] : orders)
783 tree.restart(++
seed);
784 ASSERT_TRUE(insert_all(tree, insertion, Checks::searches_too))
785 <<
"inserting " << inserting;
786 ASSERT_TRUE(remove_all(tree, removal, Checks::searches_too))
787 <<
"removing " << removing <<
" after inserting " << inserting;
788 ASSERT_EQ(tree.size(), 0u);
794 auto & tree = this->tree;
797 for (
const bool ascending : {
true,
false})
799 tree.restart(ascending ? 1 : 2);
800 for (
int i = 1; i <= n; ++i)
802 ASSERT_TRUE(tree.insert(ascending ? i : n + 1 - i));
805 ASSERT_TRUE(tree.check()) <<
"after " << i <<
" insertions";
808 ASSERT_TRUE(tree.deep_check());
810 for (
int i = 1; i <= n; ++i)
812 ASSERT_TRUE(tree.remove(ascending ? i : n + 1 - i));
815 ASSERT_TRUE(tree.check()) <<
"after " << i <<
" removals";
818 ASSERT_EQ(tree.size(), 0u);
824 auto & tree = this->tree;
827 for (
int i = 0; i < n; ++i)
829 ASSERT_TRUE(tree.insert_dup(7));
830 ASSERT_TRUE(tree.deep_check()) <<
"after " << i + 1 <<
" insertions of the same key";
832 ASSERT_TRUE(tree.insert(7));
833 ASSERT_TRUE(tree.check());
835 for (
int i = 0; i < n; ++i)
837 ASSERT_TRUE(tree.remove(7));
838 ASSERT_TRUE(tree.deep_check()) <<
"after " << i + 1 <<
" removals of the same key";
840 ASSERT_EQ(tree.size(), 0u);
841 ASSERT_TRUE(tree.remove(7));
846 auto & tree = this->tree;
847 const auto orders = adverse_orders(60);
848 unsigned long seed = 0;
850 for (
const auto & [inserting, insertion] : orders)
851 for (
const auto & [removing, removal] : orders)
853 tree.restart(++
seed);
854 for (
const int i : insertion)
856 ASSERT_TRUE(tree.insert_dup(i % 5));
857 ASSERT_TRUE(tree.deep_check()) <<
"inserting " << inserting;
859 for (
const int i : removal)
861 ASSERT_TRUE(tree.remove(i % 5));
862 ASSERT_TRUE(tree.deep_check())
863 <<
"removing " << removing <<
" after inserting " << inserting;
865 ASSERT_EQ(tree.size(), 0u);
875TYPED_TEST(PositionalRemovalBattery, EverySequenceOfPositionsOfUpToSevenKeys)
877 auto & tree = this->tree;
878 unsigned long seed = 0;
880 for (
int n = 1; n <= 7; ++n)
881 for (
const auto & [name, insertion] : adverse_orders(n))
883 std::vector<size_t> positions(n, 0);
886 tree.restart(++
seed);
887 for (
const int key : insertion)
888 ASSERT_TRUE(tree.insert(key));
890 for (
const size_t i : positions)
892 ASSERT_TRUE(tree.remove_pos(i)) <<
"inserting " << name <<
", " << n <<
" keys";
893 ASSERT_TRUE(tree.check())
894 <<
"after removing the position " << i <<
", inserting " << name <<
", " << n
897 ASSERT_EQ(tree.size(), 0u);
901 while (digit >= 0
and positions[digit] + 1 >=
static_cast<size_t>(n - digit))
902 positions[digit--] = 0;
910TYPED_TEST(PositionalRemovalBattery, RemovePosBeyondTheLastKeyThrows)
915 for (
const int key : {5, 3, 8, 1, 4})
916 ASSERT_NE(tree.insert(pool.
make(key)),
nullptr);
918 EXPECT_THROW(tree.remove_pos(5), std::out_of_range);
919 EXPECT_TRUE(tree.verify());
920 EXPECT_EQ(tree.size(), 5u);
922 auto * removed = tree.remove_pos(4);
923 ASSERT_NE(removed,
nullptr);
924 EXPECT_EQ(
KEY(removed), 8);
925 EXPECT_TRUE(tree.verify());
926 EXPECT_EQ(tree.size(), 4u);
934 EXPECT_THROW(tree.select(0), std::out_of_range);
936 for (
const int key : {5, 3, 8, 1, 4})
937 ASSERT_NE(tree.insert(pool.
make(key)),
nullptr);
939 EXPECT_EQ(
KEY(tree.select(4)), 8);
940 EXPECT_THROW(tree.select(5), std::out_of_range);
941 EXPECT_THROW(tree.select(100), std::out_of_range);
942 EXPECT_TRUE(tree.verify());
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
#define DIFF(p)
Access the balance factor of node p.
WeightedDigraph::Node Node
size_t size_t int32_t * out
Hybrid top-down/bottom-up red-black tree with rank support.
Minimal std::expected-style result type for C++20.
QuadTree - Hierarchical spatial index for 2D points.
Owns the nodes of a tree, which does not free them.
Node * make(const int key)
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
DynArray< Graph::Node * > nodes
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
and
Check uniqueness with explicit hash + equality functors.
Fw_Itor remove(Fw_Itor __first, const Fw_Itor &__last, const T &__value)
Remove elements equal to a value.
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
void next()
Advance all underlying iterators (bounds-checked).
::testing::Types< Avl_Tree_Rk< int >, Rb_Tree_Rk< int >, TdRbTreeRk< int >, HtdRbTreeRk< int >, Treap_Rk< int >, Rand_Tree< int >, Splay_Tree_Rk< int > > Ranked_Trees
The trees whose nodes count the nodes of their subtree.
::testing::Types< BinTree< int >, Avl_Tree< int >, Avl_Tree_Rk< int >, Rb_Tree< int >, Rb_Tree_Rk< int >, TdRbTree< int >, TdRbTreeRk< int >, HtdRbTree< int >, HtdRbTreeRk< int >, Treap< int >, Treap_Rk< int >, Rand_Tree< int >, Splay_Tree< int >, Splay_Tree_Rk< int > > All_Trees
Every binary search tree of the library.
#define RED
Red color constant (newly inserted nodes are red)
TYPED_TEST(SearchTreeBattery, EveryInsertionOrderOfUpToEightKeys)
What the tests of the binary search trees share: the list of tree types, what each node carries,...
Randomized binary search tree.
Extended treap (a special type of randomized binary search tree) which manages selection and splittin...
Names the instances of a typed test suite after their tree.