MCPcopy Create free account
hub / github.com/ConorWilliams/libfork / build_tree

Function build_tree

test/source/core/unbalanced.cpp:51–97  ·  view source on GitHub ↗

* @brief Build an unbalanced tree containing all the numbers from 0 to n - 1. */

Source from the content-addressed store, hash-verified

49 * @brief Build an unbalanced tree containing all the numbers from 0 to n - 1.
50 */
51auto build_tree(int n, double skew) -> std::unique_ptr<tree> {
52
53 REQUIRE(n > 0);
54 REQUIRE(skew > 0);
55 REQUIRE(skew < 1);
56
57 if (n < 1) {
58 return nullptr;
59 }
60
61 xoshiro rng{seed, std::random_device{}};
62
63 std::vector<int> vals;
64
65 for (int i = 0; i < n; ++i) {
66 vals.push_back(i);
67 }
68
69 std::shuffle(vals.begin(), vals.end(), rng);
70
71 std::unique_ptr<tree> root = nullptr;
72 std::uniform_real_distribution<double> dist{0, 1};
73
74 for (auto val : vals) {
75 if (dist(rng) < skew) {
76 root = std::make_unique<tree>(tree{val, std::move(root), nullptr});
77 } else {
78 root = std::make_unique<tree>(tree{val, nullptr, std::move(root)});
79 }
80 }
81
82 auto untwist = [&](auto &self, tree &tree) -> void {
83 if (dist(rng) < 0.5) {
84 std::swap(tree.left, tree.right);
85 }
86 if (tree.left) {
87 self(self, *tree.left);
88 }
89 if (tree.right) {
90 self(self, *tree.right);
91 }
92 };
93
94 untwist(untwist, *root);
95
96 return root;
97}
98
99LF_NOINLINE auto find(tree const &root, int val) -> bool {
100

Callers 1

unbalanced.cppFile · 0.85

Calls 1

selfFunction · 0.85

Tested by

no test coverage detected