From dee6d2782db5c9d5bbab1bbb8d2bd9ff9f6fd34a Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Wed, 27 Dec 2023 11:07:16 +0000 Subject: - Added solutions by Ulrich Rieke. - Added solutions by Dave Jacoby. - Added solutions by Stephen G Lynn. --- challenge-249/ulrich-rieke/cpp/ch-2.cpp | 63 +++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100755 challenge-249/ulrich-rieke/cpp/ch-2.cpp (limited to 'challenge-249/ulrich-rieke/cpp/ch-2.cpp') diff --git a/challenge-249/ulrich-rieke/cpp/ch-2.cpp b/challenge-249/ulrich-rieke/cpp/ch-2.cpp new file mode 100755 index 0000000000..8f52f5dcfb --- /dev/null +++ b/challenge-249/ulrich-rieke/cpp/ch-2.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include + +bool isValid( const std::vector & permu , const std::vector & the_is , + const std::vector & the_ds ) { + for ( int i = 0 ; i < the_is.size( ) ; i++ ) { + int pos = the_is[ i ] ; + if ( permu[pos] >= permu[ pos + 1] ) { + return false ; + } + } + for ( int i = 0 ; i < the_ds.size( ) ; i++ ) { + int pos = the_ds[ i ] ; + if ( permu[pos] <= permu[ pos + 1 ] ) { + return false ; + } + } + return true ; +} + +int main( ) { + std::cout << "Please enter a string consisting of capital I and D only!\n" ; + std::string line ; + std::cin >> line ; + std::vector ipositions ; + std::vector dpositions ; + for ( int i = 0 ; i < line.length( ) ; i++ ) { + if ( line.substr( i , 1 ) == "I" ) + ipositions.push_back( i ) ; + else + dpositions.push_back( i ) ; + } + int len = line.length( ) ; + std::vector numbers ( len + 1 ) ; + std::iota( numbers.begin( ) , numbers.end( ) , 0 ) ; + std::vector result ; + if ( dpositions.empty( ) ) { + result = numbers ; + } + else { + if ( ipositions.empty( ) ) { + result = numbers ; + std::reverse( result.begin( ) , result.end( ) ) ; + } + else { + while ( std::next_permutation( numbers.begin( ) , numbers.end( ) ) ) { + if ( isValid( numbers, ipositions, dpositions ) ) { + result = numbers ; + break ; + } + } + } + } + std::cout << "( " ; + for ( int i : result ) { + std::cout << i << " " ; + } + std::cout << " )\n" ; + return 0 ; +} -- cgit