From a6233090f6700d2c4b34d30c9e50c6b113b722d2 Mon Sep 17 00:00:00 2001 From: deadmarshal Date: Thu, 12 Oct 2023 13:16:43 +0330 Subject: TWC238 --- challenge-238/deadmarshal/cpp/ch-2.cpp | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 challenge-238/deadmarshal/cpp/ch-2.cpp (limited to 'challenge-238/deadmarshal/cpp/ch-2.cpp') diff --git a/challenge-238/deadmarshal/cpp/ch-2.cpp b/challenge-238/deadmarshal/cpp/ch-2.cpp new file mode 100644 index 0000000000..e2c00022aa --- /dev/null +++ b/challenge-238/deadmarshal/cpp/ch-2.cpp @@ -0,0 +1,55 @@ +#include +#include +#include + +template +T product(T n) +{ + T prod = 1; + while(n) + { + prod *= n % 10; + n /= 10; + } + return prod; +} + +template +T helper(T n) +{ + T sum = 0; + while(n >= 10) + { + sum++; + n = product(n); + } + return sum; +} + +template +void persistence_sort(std::vector& v) +{ + std::sort(v.begin(),v.end(),[](T a, T b){ + T ha = helper(a), hb = helper(b); + return ha == hb ? a < b : ha < hb; + }); +} + +template +std::ostream &operator<<(std::ostream &os, + const std::vector& vec) +{ + for(const auto &e : vec) os << e << ' '; + os << "\n"; + return os; +} + +int main() +{ + std::vector vec1{15,99,1,34},vec2{50,25,33,22}; + persistence_sort(vec1); + persistence_sort(vec2); + std::cout << vec1 << vec2; + return 0; +} + -- cgit