From eb98e39e73f94883aa8975576dcf1bd7b30db182 Mon Sep 17 00:00:00 2001 From: Mohammad Sajid Anwar Date: Thu, 12 Sep 2024 15:14:05 +0100 Subject: - Added solutions by Ulrich Rieke. --- challenge-286/ulrich-rieke/cpp/ch-2.cpp | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100755 challenge-286/ulrich-rieke/cpp/ch-2.cpp (limited to 'challenge-286/ulrich-rieke/cpp/ch-2.cpp') diff --git a/challenge-286/ulrich-rieke/cpp/ch-2.cpp b/challenge-286/ulrich-rieke/cpp/ch-2.cpp new file mode 100755 index 0000000000..7b1579b314 --- /dev/null +++ b/challenge-286/ulrich-rieke/cpp/ch-2.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include + +//routine for splitting a string at a given delimiter +std::vector split( const std::string & text , const char + delimiter ) { + std::vector tokens ; + std::istringstream istr { text } ; + std::string word ; + while ( std::getline( istr, word , delimiter )) { + tokens.push_back( word ) ; + } + return tokens ; +} + +int main( ) { + std::cout << "Enter 2 ^ n integers, where n is a positive integer!\n" ; + std::string line ; + std::getline( std::cin , line ) ; + auto tokens = split( line , ' ' ) ; + std::vector numbers ; + for ( auto s : tokens ) + numbers.push_back( std::stoi( s ) ) ; + bool last_was_min = false ;//did we determine the minimum last time ? + while ( numbers.size( ) > 1 ) { + std::vector> allPairs ;// all neighbouring pairs + for ( int i = 0 ; i < numbers.size( ) - 1 ; i += 2 ) { + allPairs.push_back( std::make_pair( numbers[i] , numbers[i + 1] )) ; + } + std::vector intermediate ; //for the minima and maxima + for ( auto it = allPairs.begin( ) ; it != allPairs.end( ) ; it++ ) { + if ( last_was_min ) { + intermediate.push_back( std::max( it->first , it->second ) ) ; + last_was_min = false ; //toggle the boolean value + } + else { + intermediate.push_back( std::min( it->first , it->second ) ) ; + last_was_min = true ; + } + } + numbers = intermediate ; + intermediate.clear( ) ; + } + std::cout << *numbers.begin( ) << '\n' ; + return 0 ; +} -- cgit