diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2023-12-27 11:07:16 +0000 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2023-12-27 11:07:16 +0000 |
| commit | dee6d2782db5c9d5bbab1bbb8d2bd9ff9f6fd34a (patch) | |
| tree | b79d0bb2bd38475dc5c7d1980013a81daed4facc /challenge-249/ulrich-rieke/cpp/ch-2.cpp | |
| parent | df882a75e7d8032373ef08d3c6967a31745e057c (diff) | |
| download | perlweeklychallenge-club-dee6d2782db5c9d5bbab1bbb8d2bd9ff9f6fd34a.tar.gz perlweeklychallenge-club-dee6d2782db5c9d5bbab1bbb8d2bd9ff9f6fd34a.tar.bz2 perlweeklychallenge-club-dee6d2782db5c9d5bbab1bbb8d2bd9ff9f6fd34a.zip | |
- Added solutions by Ulrich Rieke.
- Added solutions by Dave Jacoby.
- Added solutions by Stephen G Lynn.
Diffstat (limited to 'challenge-249/ulrich-rieke/cpp/ch-2.cpp')
| -rwxr-xr-x | challenge-249/ulrich-rieke/cpp/ch-2.cpp | 63 |
1 files changed, 63 insertions, 0 deletions
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 <string>
+#include <iostream>
+#include <algorithm>
+#include <vector>
+#include <numeric>
+
+bool isValid( const std::vector<int> & permu , const std::vector<int> & the_is ,
+ const std::vector<int> & 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<int> ipositions ;
+ std::vector<int> 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<int> numbers ( len + 1 ) ;
+ std::iota( numbers.begin( ) , numbers.end( ) , 0 ) ;
+ std::vector<int> 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 ;
+}
|
