1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-21 16:13:47 +01:00

4kyu(cpp): add „Memoized Log Cutting“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-09-16 17:33:16 +02:00
parent 342dca927f
commit c9d717eee3
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 69 additions and 0 deletions

View file

@ -0,0 +1,68 @@
#include <map>
#include <vector>
// Your new function as given to you by me, your boss.
int cut_log(const std::vector<int>& p, int n)
{
std::map<int, int> cache;
// Some array to store calculated values
for (int j = 1; j <= n; j++) {
cache[j] = (j < static_cast<int>(p.size())) ? p[j] : 0;
for (int i = 1; i < j; i++) { // Two nested loops = Θ(n^2)
cache[j] = std::max(cache[j], cache[i] + cache[j - i]);
}
}
return cache[n];
}
#pragma region tests
#include <gtest/gtest.h>
static const std::vector<int>& p()
{
static std::vector<int> _p({ 0, 1, 5, 8, 9, 10, 17, 17, 20, 24,
30, 32, 35, 39, 43, 43, 45, 49, 50, 54,
57, 60, 65, 68, 70, 74, 80, 81, 84, 85,
87, 91, 95, 99, 101, 104, 107, 112, 115, 116,
119, 121, 125, 129, 131, 134, 135, 140, 143, 145,
151 });
return _p;
}
TEST(sample, one)
{
ASSERT_EQ(cut_log(p(), 1), 1);
}
TEST(sample, five)
{
ASSERT_EQ(cut_log(p(), 5), 13);
}
TEST(sample, eight)
{
ASSERT_EQ(cut_log(p(), 8), 22);
}
TEST(sample, ten)
{
ASSERT_EQ(cut_log(p(), 10), 30);
}
TEST(sample, twenty_two)
{
ASSERT_EQ(cut_log(p(), 22), 65);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#pragma endregion /* tests */

View file

@ -41,6 +41,7 @@
- [Infix to Postfix Converter](https://www.codewars.com/kata/52e864d1ffb6ac25db00017f) - [solution](4kyu/infix_to_postfix_converter)
- [Range Extraction](https://www.codewars.com/kata/51ba717bb08c1cd60f00002f) - [solution](4kyu/range_extraction)
- [Shortest Knight Path](https://www.codewars.com/kata/549ee8b47111a81214000941) - [solution](4kyu/shortest_knight_path)
- [Memoized Log Cutting](https://www.codewars.com/kata/54b058ce56f22dc6fe0011df) - [solution](4kyu/memoized_log_cutting)
### JS