1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <initializer_list>
// return true if a and b increase or decrease by a factor of 10
bool increase_or_decrease_by_10( int a, int b )
{
return a == b*10 || b == a*10 ;
}
// return true if elements at pos and pos+1 increase or decrease by a factor of 10
bool increase_or_decrease_by_10( const int array[], std::size_t pos )
{
return increase_or_decrease_by_10( array[pos], array[pos+1] ) ;
}
std::size_t cnt_consecutive_increase_or_decrease_by_10( const int array[], std::size_t num_elements )
{
if( num_elements < 2 ) return 0 ; // nothing more to be done; end of recursion
// handle the elements at positions zero and one here,
// handle the rest of the array (elements at positions one and two etc. ) recursively
return increase_or_decrease_by_10( array, 0 ) // 1 if the first two items increase or decrease by a factor of 10
+ cnt_consecutive_increase_or_decrease_by_10( array+1, num_elements-1 ) ; // count for the rest of the array (recursive)
}
void test_it( std::initializer_list<int> ilist )
{
std::cout << "[ " ;
constexpr std::size_t MAX_SZ = 100'000 ;
int array[MAX_SZ] ;
if( ilist.size() > MAX_SZ )
return void( std::cerr << "*** error *** too many elements\n" ) ;
std::size_t pos = 0 ;
for( int v : ilist )
{
array[pos++] = v ;
std::cout << v << ' ' ;
}
std::cout << "] ==> " << cnt_consecutive_increase_or_decrease_by_10( array, ilist.size() ) << '\n' ;
}
int main()
{
test_it( { 1, 10, 20 } ) ; // 1
test_it( { 100, 10, 20, 200 } ) ; // 2
test_it( { 1000, 100, 10, 1, 10 } ) ; // 4
test_it( { 10, 20, 33, 340 } ) ; // 0
test_it( { 1, 10, 200, 2000, 200, 20, 2, 400, 4000, 400, 40, 4, 90 } ) ; // 9
}
|