37# include <gtest/gtest.h>
48 size_t brute_cost(
const Array<size_t> & dims,
const size_t i,
const size_t j)
53 size_t best = std::numeric_limits<size_t>::max();
54 for (
size_t k = i;
k < j; ++
k)
56 const size_t left = brute_cost(dims, i,
k);
57 const size_t right = brute_cost(dims,
k + 1, j);
58 const size_t here = dims[i] * dims[
k + 1] * dims[j + 1];
59 const size_t total = left + right + here;
68 const size_t i,
const size_t j)
72 const size_t k =
split[i][j];
73 return split_cost(dims, split, i,
k)
74 + split_cost(dims, split,
k + 1, j)
75 + dims[i] * dims[
k + 1] * dims[j + 1];
80TEST(MatrixChain, CLRS_Example)
85 EXPECT_EQ(
r.min_multiplications, 15125u);
86 EXPECT_FALSE(
r.parenthesization.empty());
89TEST(MatrixChain, SingleMatrix)
93 EXPECT_EQ(
r.min_multiplications, 0u);
94 EXPECT_EQ(
r.parenthesization,
"A1");
97TEST(MatrixChain, TwoMatrices)
101 EXPECT_EQ(
r.min_multiplications, 6000u);
104TEST(MatrixChain, ThreeMatrices)
111 EXPECT_EQ(
r.min_multiplications, 4500u);
132TEST(MatrixChain, ParenthesizationWellFormed)
138 for (
int i = 1; i <= 6; ++i)
140 std::string name =
"A" + std::to_string(i);
141 EXPECT_NE(
r.parenthesization.find(name), std::string::npos)
142 <<
"Missing " << name <<
" in: " <<
r.parenthesization;
147 for (
char c :
r.parenthesization)
149 if (c ==
'(') ++depth;
150 else if (c ==
')') --depth;
156TEST(MatrixChain, IdenticalDimensions)
162 EXPECT_EQ(
r.min_multiplications, 375u);
165TEST(MatrixChain, SplitTableMatchesReportedCost)
169 const size_t n = dims.
size() - 1;
170 EXPECT_EQ(split_cost(dims,
r.split, 0, n - 1),
r.min_multiplications);
173TEST(MatrixChain, RandomSmallVsBruteForce)
175 std::mt19937
rng(20260226);
176 for (
int trial = 0; trial < 120; ++trial)
178 const size_t n = 2 +
rng() % 6;
181 for (
size_t i = 0; i <= n; ++i)
182 dims.
append(1 +
static_cast<size_t>(
rng() % 25));
185 const size_t brute = brute_cost(dims, 0, n - 1);
186 EXPECT_EQ(
r.min_multiplications, brute);
187 EXPECT_EQ(split_cost(dims,
r.split, 0, n - 1),
r.min_multiplications);
191TEST(MatrixChain, OverflowThrows)
193 const size_t M = std::numeric_limits<size_t>::max();
Matrix-chain multiplication optimization via interval DP.
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Main namespace for Aleph-w library functions.
Matrix_Chain_Result matrix_chain_order(const Array< size_t > &dims)
Compute the optimal matrix-chain multiplication order.
size_t matrix_chain_min_cost(const Array< size_t > &dims)
Compute only the minimum multiplication cost (value only).
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.