From b9d382731b7e148a13e10c974772c94650520579 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 3 Sep 2022 23:52:07 +0200 Subject: [PATCH] =?UTF-8?q?problems(cpp):=20add=20=E2=80=9E967.=20Numbers?= =?UTF-8?q?=20With=20Same=20Consecutive=20Differences=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...bers-with-same-consecutive-differences.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 problems/numbers-with-same-consecutive-differences.cpp diff --git a/problems/numbers-with-same-consecutive-differences.cpp b/problems/numbers-with-same-consecutive-differences.cpp new file mode 100644 index 0000000..dfdb7b4 --- /dev/null +++ b/problems/numbers-with-same-consecutive-differences.cpp @@ -0,0 +1,74 @@ +#include + +namespace { + +void nums_same_consec_diff(int n, int k, std::vector& nums, int number) +{ + if (n == 0) { + nums.push_back(number); + return; + } + + auto last_digit = number % 10; + for (int d = 0; d < 10; d++) { + if (std::abs(last_digit - d) == k) { + nums_same_consec_diff(n - 1, k, nums, number * 10 + d); + } + } +} + +} + +class Solution { +public: + std::vector numsSameConsecDiff(int n, int k) + { + std::vector nums; + + for (int d = 1; d < 10; d++) { + nums_same_consec_diff(n - 1, k, nums, d); + } + + return nums; + } +}; + +#pragma region tests + +#include + +TEST(examples, first) +{ + Solution s; + ASSERT_EQ(s.numsSameConsecDiff(3, 7), (std::vector { 181, 292, 707, 818, 929 })); +} + +TEST(examples, second) +{ + Solution s; + ASSERT_EQ(s.numsSameConsecDiff(2, 1), + (std::vector { 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, + 87, 89, 98 })); +} + +TEST(same, two) +{ + Solution s; + ASSERT_EQ(s.numsSameConsecDiff(2, 0), + (std::vector { 11, 22, 33, 44, 55, 66, 77, 88, 99 })); +} + +TEST(same, three) +{ + Solution s; + ASSERT_EQ(s.numsSameConsecDiff(3, 0), + (std::vector { 111, 222, 333, 444, 555, 666, 777, 888, 999 })); +} + +int main(int argc, char** argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + +#pragma endregion /* tests */