Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
search_trees_battery_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 / \ | | ___ _ __ | |__ __ __
5 / _ \ | |/ _ \ '_ \| '_ \ ____\ \ /\ / /
6 / ___ \| | __/ |_) | | | |_____\ V V /
7 /_/ \_\_|\___| .__/|_| |_| \_/\_/
8 |_|
9
10 This file is part of Aleph-w library
11
12 Copyright (c) 2002-2026 Leandro Rabindranath Leon
13
14 Permission is hereby granted, free of charge, to any person obtaining a copy
15 of this software and associated documentation files (the "Software"), to deal
16 in the Software without restriction, including without limitation the rights
17 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 copies of the Software, and to permit persons to whom the Software is
19 furnished to do so, subject to the following conditions:
20
21 The above copyright notice and this permission notice shall be included in all
22 copies or substantial portions of the Software.
23
24 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 SOFTWARE.
31*/
32
61
62#include <algorithm>
63#include <iterator>
64#include <numeric>
65#include <optional>
66#include <random>
67#include <set>
68#include <sstream>
69#include <stdexcept>
70#include <utility>
71
72using namespace Aleph;
73using namespace search_trees_test;
74
75using ::testing::AssertionFailure;
76using ::testing::AssertionResult;
77using ::testing::AssertionSuccess;
78
79namespace
80{
81 template <class Tree>
82 concept Sized_Tree = requires(const Tree & tree) { tree.size(); };
83
84 template <class Tree>
85 concept Ranked_Tree = requires(Tree & tree, int key, size_t i)
86 {
87 tree.select(i);
88 tree.position(key);
89 };
90
91 template <class Tree>
92 concept Removes_By_Position = requires(Tree & tree, size_t i) { tree.remove_pos(i); };
93
94 std::string to_string(const std::vector<int> & keys)
95 {
96 std::ostringstream out;
97 out << '{';
98 for (size_t i = 0; i < keys.size(); ++i)
99 out << (i == 0 ? "" : ", ") << keys[i];
100 out << '}';
101 return out.str();
102 }
103
104 // The least number of nodes of an AVL tree of height `h`.
105 size_t min_avl_nodes(const int h) noexcept
106 {
107 size_t below = 0, at = 1; // heights 0 and 1
108 if (h == 0)
109 return 0;
110 for (int i = 1; i < h; ++i)
111 {
112 const size_t next = at + below + 1;
113 below = at;
114 at = next;
115 }
116 return at;
117 }
118
119 // A tree and the multiset that says what the tree must hold.
120 template <class Tree>
121 class Checked_Tree
122 {
123 public:
124 using Node = typename Tree::Node;
125
126 private:
127 std::optional<Tree> tree;
128 std::multiset<int> model;
129 std::vector<std::unique_ptr<Node>> nodes; // every node ever made
130 std::vector<Node *> spare; // the ones out of the tree
131 std::vector<int> keys; // the last traversal
132 int height = 0; // and the height it saw
133
134 Node * take_node(const int key)
135 {
136 if (spare.empty())
137 {
138 nodes.push_back(std::make_unique<Node>(key));
139 return nodes.back().get();
140 }
141
142 Node * p = spare.back();
143 spare.pop_back();
144 p->reset();
145 KEY(p) = key;
146 return p;
147 }
148
149 void walk(Node * p, const int depth)
150 {
151 if (p == Node::NullPtr)
152 return;
153 if (depth > height)
154 height = depth;
155 walk(LLINK(p), depth + 1);
156 keys.push_back(KEY(p));
157 walk(RLINK(p), depth + 1);
158 }
159
160 AssertionResult check_ranks()
161 {
162 if constexpr (Ranked_Tree<Tree>)
163 {
164 size_t i = 0;
165 for (const int key : model)
166 {
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;
170
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";
176 ++i;
177 }
178
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";
182 }
183
184 return AssertionSuccess();
185 }
186
187 public:
188 explicit Checked_Tree(const unsigned long seed = 1) { restart(seed); }
189
190 // Leaves the tree empty, as if just made with the given seed.
191 void restart([[maybe_unused]] const unsigned long seed)
192 {
193 spare.clear();
194 for (auto & p : nodes)
195 spare.push_back(p.get());
196 model.clear();
197 tree.emplace();
198 if constexpr (Seeded_Tree<Tree>)
199 tree->set_seed(seed);
200 }
201
202 [[nodiscard]] size_t size() const noexcept { return model.size(); }
203
204 [[nodiscard]] bool has(const int key) const { return model.count(key) > 0; }
205
206 [[nodiscard]] const std::multiset<int> & expected() const noexcept { return model; }
207
208 // The shape of the tree, and what its nodes say of its balance.
209 [[nodiscard]] std::string signature()
210 {
211 std::string out;
212 write_signature(tree->getRoot(), out);
213 return out;
214 }
215
216 AssertionResult insert(const int key)
217 {
218 const bool is_new = not has(key);
219 Node * p = take_node(key);
220 Node * q = tree->insert(p);
221
222 if (not is_new)
223 {
224 spare.push_back(p);
225 if (q != nullptr)
226 return AssertionFailure() << "insert(" << key << ") accepted a key that was in the tree";
227 return AssertionSuccess();
228 }
229
230 if (q != p)
231 return AssertionFailure() << "insert(" << key << ") did not return the node of the new key";
232 model.insert(key);
233 return AssertionSuccess();
234 }
235
236 // The insertion that the sets and maps of the library use.
237 AssertionResult search_or_insert(const int key)
238 {
239 const bool is_new = not has(key);
240 Node * p = take_node(key);
241 Node * q = tree->search_or_insert(p);
242
243 if (not is_new)
244 {
245 spare.push_back(p);
246 if (q == 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();
253 }
254
255 if (q != p)
256 return AssertionFailure() << "search_or_insert(" << key
257 << ") did not return the node of the new key";
258 model.insert(key);
259 return AssertionSuccess();
260 }
261
262 AssertionResult insert_dup(const int key)
263 {
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";
267 model.insert(key);
268 return AssertionSuccess();
269 }
270
271 AssertionResult remove(const int key)
272 {
273 const auto it = model.find(key);
274 Node * p = tree->remove(key);
275
276 if (it == model.end())
277 {
278 if (p != nullptr)
279 return AssertionFailure() << "remove(" << key << ") gave a node for an absent key";
280 return AssertionSuccess();
281 }
282
283 if (p == nullptr or p == Node::NullPtr)
284 return AssertionFailure() << "remove(" << key << ") did not find a key of the tree";
285 if (KEY(p) != key)
286 return AssertionFailure() << "remove(" << key << ") gave the node of key " << KEY(p);
287
288 model.erase(it);
289 spare.push_back(p);
290 return AssertionSuccess();
291 }
292
293 // Removes the key at the position `i` of the order, in the trees that
294 // can do it.
295 AssertionResult remove_pos(const size_t i)
296 {
297 if constexpr (Removes_By_Position<Tree>)
298 {
299 const auto it = std::next(model.begin(), static_cast<std::ptrdiff_t>(i));
300 Node * p = tree->remove_pos(i);
301
302 if (p == nullptr or p == Node::NullPtr)
303 return AssertionFailure() << "remove_pos(" << i << ") gave no node";
304 if (KEY(p) != *it)
305 return AssertionFailure() << "remove_pos(" << i << ") gave the node of key " << KEY(p)
306 << " and the key there is " << *it;
307
308 model.erase(it);
309 spare.push_back(p);
310 return AssertionSuccess();
311 }
312 else
313 return AssertionFailure() << "the tree has no remove_pos(" << i << ")";
314 }
315
316 AssertionResult search(const int key)
317 {
318 Node * p = tree->search(key);
319
320 if (not has(key))
321 {
322 if (p != nullptr)
323 return AssertionFailure() << "search(" << key << ") gave a node for an absent key";
324 return AssertionSuccess();
325 }
326
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();
330 }
331
332 // The invariants of the tree and its keys in order.
333 AssertionResult check()
334 {
335 Node * root = tree->getRoot();
336
337 if (not tree->verify())
338 return AssertionFailure() << "verify() is false";
339
340 keys.clear();
341 height = 0;
342 walk(root, 1);
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()));
346
347 if constexpr (Sized_Tree<Tree>)
348 if (tree->size() != model.size())
349 return AssertionFailure() << "size() is " << tree->size() << " with " << model.size()
350 << " keys";
351
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";
356
357 if constexpr (Colored_Node<Node>)
358 {
359 // A path has no two red nodes in a row, so half of the height is
360 // black, and a black height of b takes 2^b - 1 nodes at least.
361 // The root can be red: these trees do not force it to be black,
362 // which does not change the bound
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()
366 << " nodes";
367 }
368
369 return AssertionSuccess();
370 }
371
372 // check(), and then every key is found where it must be. Searching
373 // restructures a self-adjusting tree, so the invariants are checked
374 // again at the end.
375 AssertionResult deep_check()
376 {
377 if (auto ok = check(); not ok)
378 return ok;
379
380 if (not model.empty())
381 if (auto ok = search(*model.begin() - 1); not ok)
382 return ok;
383
384 for (auto it = model.begin(); it != model.end(); it = model.upper_bound(*it))
385 {
386 if (auto ok = search(*it); not ok)
387 return ok;
388 if (not has(*it + 1))
389 if (auto ok = search(*it + 1); not ok)
390 return ok;
391 }
392
393 if (auto ok = check_ranks(); not ok)
394 return ok;
395
396 return check();
397 }
398
399 private:
400 static void write_signature(Node * p, std::string & out)
401 {
402 if (p == Node::NullPtr)
403 {
404 out += '.';
405 return;
406 }
407
408 out += std::to_string(KEY(p));
409 if constexpr (Colored_Node<Node>)
410 out += COLOR(p) == RED ? 'r' : 'b';
411 if constexpr (Avl_Balanced_Node<Node>)
412 out += DIFF(p) < 0 ? '-' : DIFF(p) > 0 ? '+' : '=';
413 out += '(';
414 write_signature(LLINK(p), out);
415 write_signature(RLINK(p), out);
416 out += ')';
417 }
418 };
419
420 // What is checked after each operation of a sequence: the invariants and
421 // the keys in order, or also the search of every key.
422 enum class Checks { invariants, searches_too };
423
424 template <class Tree>
425 AssertionResult checked(Checked_Tree<Tree> & tree, const Checks checks)
426 {
427 return checks == Checks::searches_too ? tree.deep_check() : tree.check();
428 }
429
430 // Inserts the keys, with a check after each one.
431 template <class Tree>
432 AssertionResult insert_all(Checked_Tree<Tree> & tree, const std::vector<int> & order,
433 const Checks checks)
434 {
435 for (const int key : order)
436 {
437 if (auto ok = tree.insert(key); not ok)
438 return ok;
439 if (auto ok = checked(tree, checks); not ok)
440 return ok << " after inserting " << key;
441 }
442 return AssertionSuccess();
443 }
444
445 // Removes the keys, with a check after each one; a key just removed is no
446 // longer there to be removed.
447 template <class Tree>
448 AssertionResult remove_all(Checked_Tree<Tree> & tree, const std::vector<int> & order,
449 const Checks checks)
450 {
451 for (const int key : order)
452 {
453 if (auto ok = tree.remove(key); not ok)
454 return ok;
455 if (auto ok = checked(tree, checks); not ok)
456 return ok << " after removing " << key;
457 if (tree.has(key))
458 continue; // another node with the same key remains
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";
463 }
464 return AssertionSuccess();
465 }
466
467 // The keys 1 ... n in the orders that degrade a tree that does not
468 // balance itself, or that push a balanced one always to the same side.
469 std::vector<std::pair<std::string, std::vector<int>>> adverse_orders(const int n)
470 {
471 std::vector<int> ascending(n);
472 std::iota(ascending.begin(), ascending.end(), 1);
473
474 std::vector<int> descending(ascending.rbegin(), ascending.rend());
475
476 std::vector<int> from_both_ends; // 1, n, 2, n - 1, ...
477 for (int lo = 1, hi = n; lo <= hi; ++lo, --hi)
478 {
479 from_both_ends.push_back(lo);
480 if (lo != hi)
481 from_both_ends.push_back(hi);
482 }
483
484 // n/2, n/2 + 1, n/2 - 1, ...
485 std::vector<int> from_the_middle(from_both_ends.rbegin(), from_both_ends.rend());
486
487 std::vector<int> by_halves; // the root of a perfect tree, then its children, ...
488 int top = 1;
489 while (2 * top <= n)
490 top *= 2;
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)
494 if (not used[key])
495 {
496 used[key] = true;
497 by_halves.push_back(key);
498 }
499
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]);
504
505 return {
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}};
512 }
513
514 template <class Tree>
515 class SearchTreeBattery : public ::testing::Test
516 {
517 protected:
518 Checked_Tree<Tree> tree;
519 };
520
521 TYPED_TEST_SUITE(SearchTreeBattery, All_Trees, Tree_Names);
522
523 template <class Tree>
524 class RankedTreeBattery : public ::testing::Test {};
525
526 TYPED_TEST_SUITE(RankedTreeBattery, Ranked_Trees, Tree_Names);
527
528 template <class Tree>
529 class PositionalRemovalBattery : public ::testing::Test
530 {
531 protected:
532 Checked_Tree<Tree> tree;
533 };
534
535 // The trees with remove_pos().
536 using Positional_Trees =
537 ::testing::Types<TdRbTreeRk<int>, HtdRbTreeRk<int>, Treap_Rk<int>, Rand_Tree<int>>;
538
539 TYPED_TEST_SUITE(PositionalRemovalBattery, Positional_Trees, Tree_Names);
540}
541
542// ---------------------------------------------------------------------------
543// Every sequence, in small
544// ---------------------------------------------------------------------------
545
546TYPED_TEST(SearchTreeBattery, EveryInsertionOrderOfUpToEightKeys)
547{
548 auto & tree = this->tree;
549 unsigned long sequences = 0;
550
551 for (int n = 1; n <= 8; ++n)
552 {
553 std::vector<int> order(n);
554 std::iota(order.begin(), order.end(), 1);
555
556 do
557 {
558 tree.restart(++sequences);
559 ASSERT_TRUE(insert_all(tree, order, Checks::invariants))
560 << "inserting " << to_string(order);
561 ASSERT_TRUE(tree.deep_check()) << "after inserting " << to_string(order);
562
563 // A key that is in the tree is refused, and nothing changes
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);
567 }
568 while (std::next_permutation(order.begin(), order.end()));
569 }
570
571 EXPECT_EQ(sequences, 46233ul); // 1! + 2! + ... + 8!
572}
573
574// search_or_insert() is how DynSetTree and DynMapTree insert, and each
575// tree has its own code for it.
576TYPED_TEST(SearchTreeBattery, EveryOrderOfSearchOrInsertOfUpToSevenKeys)
577{
578 auto & tree = this->tree;
579 unsigned long sequences = 0;
580
581 for (int n = 1; n <= 7; ++n)
582 {
583 std::vector<int> order(n);
584 std::iota(order.begin(), order.end(), 1);
585
586 do
587 {
588 tree.restart(++sequences);
589 for (const int key : order)
590 {
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);
594 }
595 ASSERT_TRUE(tree.deep_check()) << "after inserting " << to_string(order);
596
597 // A key that is in the tree is found, and nothing is inserted
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);
601 }
602 while (std::next_permutation(order.begin(), order.end()));
603 }
604
605 EXPECT_EQ(sequences, 5913ul); // 1! + 2! + ... + 7!
606}
607
608TYPED_TEST(SearchTreeBattery, EveryRemovalOrderFromEveryTreeOfUpToSixKeys)
609{
610 auto & tree = this->tree;
611 unsigned long seed = 0;
612 size_t shapes = 0;
613
614 for (int n = 1; n <= 6; ++n)
615 {
616 std::set<std::string> seen;
617 std::vector<int> insertion(n);
618 std::iota(insertion.begin(), insertion.end(), 1);
619
620 do
621 {
622 // The same seed builds the same tree again for each removal order
623 tree.restart(++seed);
624 for (const int key : insertion)
625 ASSERT_TRUE(tree.insert(key));
626 if (not seen.insert(tree.signature()).second)
627 continue; // these removals were already done from this tree
628
629 std::vector<int> removal(n);
630 std::iota(removal.begin(), removal.end(), 1);
631 do
632 {
633 tree.restart(seed);
634 for (const int key : insertion)
635 ASSERT_TRUE(tree.insert(key));
636
637 ASSERT_TRUE(remove_all(tree, removal, Checks::invariants))
638 << "after inserting " << to_string(insertion) << ", removing "
639 << to_string(removal);
640 ASSERT_EQ(tree.size(), 0u);
641 }
642 while (std::next_permutation(removal.begin(), removal.end()));
643 }
644 while (std::next_permutation(insertion.begin(), insertion.end()));
645
646 shapes += seen.size();
647 }
648
649 EXPECT_GE(shapes, 6u);
650 this->RecordProperty("trees", static_cast<int>(shapes));
651}
652
653TYPED_TEST(SearchTreeBattery, EveryRemovalOrderOfSevenKeysFromGivenTrees)
654{
655 auto & tree = this->tree;
656 const int n = 7;
657 unsigned long seed = 0;
658
659 for (const auto & [name, insertion] : adverse_orders(n))
660 {
661 std::vector<int> removal(n);
662 std::iota(removal.begin(), removal.end(), 1);
663 do
664 {
665 tree.restart(++seed);
666 for (const int key : insertion)
667 ASSERT_TRUE(tree.insert(key));
668
669 ASSERT_TRUE(remove_all(tree, removal, Checks::invariants))
670 << "after inserting " << to_string(insertion) << " (" << name << "), removing "
671 << to_string(removal);
672 }
673 while (std::next_permutation(removal.begin(), removal.end()));
674 }
675}
676
677// ---------------------------------------------------------------------------
678// Long random sequences
679// ---------------------------------------------------------------------------
680
681namespace
682{
683 // `num_ops` random operations on keys of [0, universe): first mostly
684 // insertions, then as many insertions as removals, then mostly removals.
685 // Then the tree is emptied.
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)
690 {
691 std::mt19937 rng(seed);
692 tree.restart(seed);
693
694 for (int i = 0; i < num_ops; ++i)
695 {
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;
699
700 AssertionResult done = AssertionSuccess();
701 const char * what = "searching";
702 if (dice < inserts)
703 {
704 what = "inserting";
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);
708 }
709 else if (dice < 80)
710 {
711 what = "removing";
712 if (Removes_By_Position<Tree> and tree.size() > 0 and rng() % 4 == 0)
713 {
714 what = "removing the key at position";
715 done = tree.remove_pos(key % tree.size());
716 }
717 else
718 done = tree.remove(key);
719 }
720 else
721 done = tree.search(key);
722
723 if (not done)
724 return done << " (operation " << i << ", seed " << seed << ")";
725
726 if (auto ok = i % 61 == 0 ? tree.deep_check() : tree.check(); not ok)
727 return ok << " after " << what << ' ' << key << " (operation " << i << ", seed "
728 << seed << ")";
729 }
730
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]);
734
735 for (const int key : rest)
736 {
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 << ")";
741 }
742
743 if (tree.size() != 0)
744 return AssertionFailure() << "the tree was not emptied";
745 return tree.deep_check();
746 }
747}
748
749// Few keys: most insertions find the key and many removals do not.
750TYPED_TEST(SearchTreeBattery, RandomOperationsOnFewKeys)
751{
752 for (const unsigned seed : {1u, 2u, 3u, 4u})
753 ASSERT_TRUE(random_operations(this->tree, seed, 24, 6000, false));
754}
755
756TYPED_TEST(SearchTreeBattery, RandomOperationsOnManyKeys)
757{
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));
761}
762
763TYPED_TEST(SearchTreeBattery, RandomOperationsWithRepeatedKeys)
764{
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));
768}
769
770// ---------------------------------------------------------------------------
771// The orders that usually break a tree
772// ---------------------------------------------------------------------------
773
774TYPED_TEST(SearchTreeBattery, AdverseInsertionAndRemovalOrders)
775{
776 auto & tree = this->tree;
777 const auto orders = adverse_orders(96);
778 unsigned long seed = 0;
779
780 for (const auto & [inserting, insertion] : orders)
781 for (const auto & [removing, removal] : orders)
782 {
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);
789 }
790}
791
792TYPED_TEST(SearchTreeBattery, LongAscendingAndDescendingRuns)
793{
794 auto & tree = this->tree;
795 const int n = 1000;
796
797 for (const bool ascending : {true, false})
798 {
799 tree.restart(ascending ? 1 : 2);
800 for (int i = 1; i <= n; ++i)
801 {
802 ASSERT_TRUE(tree.insert(ascending ? i : n + 1 - i));
803 if (i % 50 == 0)
804 {
805 ASSERT_TRUE(tree.check()) << "after " << i << " insertions";
806 }
807 }
808 ASSERT_TRUE(tree.deep_check());
809
810 for (int i = 1; i <= n; ++i)
811 {
812 ASSERT_TRUE(tree.remove(ascending ? i : n + 1 - i));
813 if (i % 50 == 0)
814 {
815 ASSERT_TRUE(tree.check()) << "after " << i << " removals";
816 }
817 }
818 ASSERT_EQ(tree.size(), 0u);
819 }
820}
821
822TYPED_TEST(SearchTreeBattery, ManyNodesWithTheSameKey)
823{
824 auto & tree = this->tree;
825 const int n = 64;
826
827 for (int i = 0; i < n; ++i)
828 {
829 ASSERT_TRUE(tree.insert_dup(7));
830 ASSERT_TRUE(tree.deep_check()) << "after " << i + 1 << " insertions of the same key";
831 }
832 ASSERT_TRUE(tree.insert(7)); // refused: the key is there
833 ASSERT_TRUE(tree.check());
834
835 for (int i = 0; i < n; ++i)
836 {
837 ASSERT_TRUE(tree.remove(7));
838 ASSERT_TRUE(tree.deep_check()) << "after " << i + 1 << " removals of the same key";
839 }
840 ASSERT_EQ(tree.size(), 0u);
841 ASSERT_TRUE(tree.remove(7)); // nothing left to remove
842}
843
844TYPED_TEST(SearchTreeBattery, FewKeysRepeatedManyTimes)
845{
846 auto & tree = this->tree;
847 const auto orders = adverse_orders(60);
848 unsigned long seed = 0;
849
850 for (const auto & [inserting, insertion] : orders)
851 for (const auto & [removing, removal] : orders)
852 {
853 tree.restart(++seed);
854 for (const int i : insertion)
855 {
856 ASSERT_TRUE(tree.insert_dup(i % 5));
857 ASSERT_TRUE(tree.deep_check()) << "inserting " << inserting;
858 }
859 for (const int i : removal)
860 {
861 ASSERT_TRUE(tree.remove(i % 5));
862 ASSERT_TRUE(tree.deep_check())
863 << "removing " << removing << " after inserting " << inserting;
864 }
865 ASSERT_EQ(tree.size(), 0u);
866 }
867}
868
869// ---------------------------------------------------------------------------
870// Access by position
871// ---------------------------------------------------------------------------
872
873// Every way of emptying a tree of up to 7 keys by positions: the first
874// position is any of the n, the second any of the n - 1 left, and so on.
875TYPED_TEST(PositionalRemovalBattery, EverySequenceOfPositionsOfUpToSevenKeys)
876{
877 auto & tree = this->tree;
878 unsigned long seed = 0;
879
880 for (int n = 1; n <= 7; ++n)
881 for (const auto & [name, insertion] : adverse_orders(n))
882 {
883 std::vector<size_t> positions(n, 0); // the i-th one is less than n - i
884 while (true)
885 {
886 tree.restart(++seed);
887 for (const int key : insertion)
888 ASSERT_TRUE(tree.insert(key));
889
890 for (const size_t i : positions)
891 {
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
895 << " keys";
896 }
897 ASSERT_EQ(tree.size(), 0u);
898
899 // The next sequence, as a counter whose digit i runs up to n - i
900 int digit = n - 1;
901 while (digit >= 0 and positions[digit] + 1 >= static_cast<size_t>(n - digit))
902 positions[digit--] = 0;
903 if (digit < 0)
904 break;
905 ++positions[digit];
906 }
907 }
908}
909
910TYPED_TEST(PositionalRemovalBattery, RemovePosBeyondTheLastKeyThrows)
911{
912 TypeParam tree;
914
915 for (const int key : {5, 3, 8, 1, 4})
916 ASSERT_NE(tree.insert(pool.make(key)), nullptr);
917
918 EXPECT_THROW(tree.remove_pos(5), std::out_of_range);
919 EXPECT_TRUE(tree.verify());
920 EXPECT_EQ(tree.size(), 5u);
921
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);
927}
928
929TYPED_TEST(RankedTreeBattery, SelectBeyondTheLastKeyThrows)
930{
931 TypeParam tree;
933
934 EXPECT_THROW(tree.select(0), std::out_of_range);
935
936 for (const int key : {5, 3, 8, 1, 4})
937 ASSERT_NE(tree.insert(pool.make(key)), nullptr);
938
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());
943}
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
#define DIFF(p)
Access the balance factor of node p.
Definition avlNode.H:95
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
long double h
Definition btreepic.C:154
size_t size_t int32_t * out
Definition ca-c-api.h:120
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.
Definition quadtree.H:126
QuadNode Node
Definition quadtree.H:128
Owns the nodes of a tree, which does not free them.
static mt19937 rng
__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)
Definition gmpfrxx.h:4138
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
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.
Definition ahAlgo.H:962
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
::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 COLOR(p)
Definition quadnode.H:59
#define RED
Red color constant (newly inserted nodes are red)
Definition rbNode.H:77
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.
bool check(GT &g)
#define RLINK(i, n)
int keys[]
#define LLINK(i, n)
ValueArg< size_t > seed
Definition testHash.C:53