diff --git a/4kyu/memoized_log_cutting/solution.cpp b/4kyu/memoized_log_cutting/solution.cpp new file mode 100644 index 0000000..02c11b9 --- /dev/null +++ b/4kyu/memoized_log_cutting/solution.cpp @@ -0,0 +1,68 @@ +#include +#include + +// Your new function as given to you by me, your boss. +int cut_log(const std::vector& p, int n) +{ + std::map cache; + + // Some array to store calculated values + for (int j = 1; j <= n; j++) { + cache[j] = (j < static_cast(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 + +static const std::vector& p() +{ + static std::vector _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 */ diff --git a/README.md b/README.md index 3a99e57..ea4ec67 100644 --- a/README.md +++ b/README.md @@ -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