Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
opbintree_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
39#include <gtest/gtest.h>
40
41#include <memory>
42#include <random>
43
44#include <opBinTree.H>
45#include <tpl_array.H>
46#include <tpl_binNode.H>
47#include <tpl_binNodeUtils.H>
48
49using namespace Aleph;
50
51namespace
52{
53 using Node = BinNode<int>;
54
55 // The cost of a tree whose keys are the indexes of p: the sum of the
56 // weight of each key times its depth, with the root at depth 1. `next`
57 // counts the nodes in order, and each one must hold the key of its
58 // place: the inorder of the tree is then 0, 1, 2..., with no key twice,
59 // which the cost does not tell of a key whose weight is zero. The weight
60 // is read with a checked access: the key is whatever the tree holds
61 double cost_of(Node * root, const Array<double> & p, const int depth, int & next)
62 {
63 if (root == Node::NullPtr)
64 return 0;
65 double cost = cost_of(LLINK(root), p, depth + 1, next);
66 EXPECT_EQ(KEY(root), next) << "the key at the place " << next << " of the inorder";
67 ++next;
68 cost += p[static_cast<size_t>(KEY(root))] * depth;
69 return cost + cost_of(RLINK(root), p, depth + 1, next);
70 }
71
72 // The least cost of a binary search tree of those weights, by the
73 // recurrence of the dynamic programming with every root tried: O(n^3)
74 double least_cost(const Array<double> & p)
75 {
76 const size_t n = p.size();
77 Array<double> cost((n + 2) * (n + 2), 0.0);
78 auto at = [n, &cost] (const size_t i, const size_t j) -> double & { return cost(i * (n + 2) + j); };
79 for (size_t len = 1; len <= n; ++len)
80 for (size_t i = 1; i + len - 1 <= n; ++i)
81 {
82 const size_t j = i + len - 1;
83 double sum = 0;
84 for (size_t k = i; k <= j; ++k)
85 sum += p(k - 1);
86 double best = at(i, i - 1) + at(i + 1, j);
87 for (size_t r = i + 1; r <= j; ++r)
88 best = std::min(best, at(i, r - 1) + at(r + 1, j));
89 at(i, j) = best + sum;
90 }
91 return n == 0 ? 0 : at(1, n);
92 }
93
94 // Frees the tree of a test when the test leaves it, also if a check
95 // throws on the way: the checked read of a weight does, for a key that
96 // is not one of the keys
97 struct Destroy_Tree
98 {
99 void operator () (Node * root) const noexcept { destroyRec(root); }
100 };
101
102 void expect_an_optimal_tree(Array<double> & p)
103 {
104 const size_t n = p.size();
105 Array<int> keys(n, 0);
106 for (size_t i = 0; i < n; ++i)
107 keys(i) = static_cast<int>(i);
108
109 const std::unique_ptr<Node, Destroy_Tree> tree(
110 build_optimal_tree<Node, int>(n == 0 ? nullptr : &keys(0), n == 0 ? nullptr : &p(0), n));
111 int next = 0;
112 const double cost = cost_of(tree.get(), p, 1, next);
113 EXPECT_EQ(next, static_cast<int>(n)) << "the nodes of the tree, with " << n << " keys";
114 EXPECT_NEAR(cost, least_cost(p), 1e-9) << "with " << n << " keys";
115 }
116}
117
118TEST(OptimalBinTree, WithoutKeysItIsEmpty)
119{
121 EXPECT_EQ((build_optimal_tree<Node, int>(nullptr, nullptr, 0)), Node::NullPtr);
122 expect_an_optimal_tree(p);
123}
124
125// Random weights, against the least cost that trying every root gives
126TEST(OptimalBinTree, ItsCostIsTheLeastOne)
127{
128 std::mt19937 rng(20261125);
129 std::uniform_real_distribution<double> weight(0.0, 1.0);
130 for (size_t n = 1; n <= 40; ++n)
131 for (int trial = 0; trial < 5; ++trial)
132 {
133 Array<double> p(n, 0.0);
134 for (size_t i = 0; i < n; ++i)
135 p(i) = weight(rng);
136 expect_an_optimal_tree(p);
137 }
138}
139
140// Equal weights, weights of zero and one key far heavier than the others
141TEST(OptimalBinTree, ItsCostIsTheLeastOneWithTiesAndZeros)
142{
143 for (size_t n = 1; n <= 33; ++n)
144 {
145 Array<double> equal(n, 0.25);
146 expect_an_optimal_tree(equal);
147
148 Array<double> zeros(n, 0.0);
149 expect_an_optimal_tree(zeros);
150
151 Array<double> some(n, 0.0);
152 for (size_t i = 0; i < n; i += 3)
153 some(i) = 1.0;
154 expect_an_optimal_tree(some);
155
156 Array<double> heavy(n, 0.001);
157 heavy(n - 1) = 1000.0;
158 expect_an_optimal_tree(heavy);
159 }
160}
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
Node for binary search tree.
#define TEST(name)
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
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
Main namespace for Aleph-w library functions.
bool equal(Itor1 beg, const Itor1 &end, Itor2 cmpBeg, BinaryPredicate op=BinaryPredicate())
Test if two ranges are equal.
Definition ahAlgo.H:482
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Optimal Binary Search Tree construction using dynamic programming.
#define RLINK(i, n)
int keys[]
#define LLINK(i, n)
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Utility functions for binary tree operations.
Basic binary tree node definitions.