From 6744c38f0df5adea467f9f58ee133c832c034715 Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Sat, 29 Aug 2020 22:18:30 +0100 Subject: [PATCH] permutation.cpp --- puzzles/training/permutation.cpp | 70 ++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 puzzles/training/permutation.cpp diff --git a/puzzles/training/permutation.cpp b/puzzles/training/permutation.cpp new file mode 100644 index 0000000..8d3f245 --- /dev/null +++ b/puzzles/training/permutation.cpp @@ -0,0 +1,70 @@ +/* +VIM: let b:cf5build="clang++ -std=c++20 -O2 -pthread -I. {SRC} -o {OUT}" +VIM: let b:cf5run="{OUT}" +*/ +#include +#include +#include + +void permutate(auto b, auto e) +{ + auto bt = std::reverse_iterator(e); + auto et = std::reverse_iterator(b); + + auto it = bt+1; + for ( ; it != et && *it >= *(it-1); ++it); + + for (auto qt = bt, rt = it-1; rt > qt; qt++, rt--){ + std::swap(*qt, *rt); + } + + if (it != et){ + auto pt = it-1; + for( ; pt != bt && *it >= *pt; --pt); + std::swap(*it, *pt); + } +} + +void test(std::string char_set) +{ + std::sort(char_set.begin(), char_set.end()); + std::string perm = char_set; + int i = 0; + do { + ++i; + std::cout << perm << '\n'; + permutate(perm.begin(), perm.end()); + } while (perm != char_set); + + std::cout << i << '\n' << "-------------------------------------\n"; +} + +int main ( void ) +{try{ + auto begin = std::chrono::high_resolution_clock::now(); + + test( "abcd" ); + test( "aab" ); + test( "aabb" ); + test( "aaabbb" ); + + //...... + + auto end = std::chrono::high_resolution_clock::now(); + std::chrono::duration seconds = end - begin; + std::cout << "Time: " << seconds.count() << std::endl; + return 0; +} +catch ( const std::exception& e ) +{ + std::cerr << std::endl + << "std::exception(\"" << e.what() << "\")." << std::endl; + return 2; +} +catch ( ... ) +{ + std::cerr << std::endl + << "unknown exception." << std::endl; + return 1; +}} +