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
|
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string_view>
bool is_symmetrical_a( const int array[], std::size_t sz )
{
// size of zero or one: symmetrical
if( sz < 2 ) return true ;
// if first element not equal to last element: not symmetrical
if( array[0] != array[sz-1] ) return false ;
// otherwise symmetrical if the middle sz-2 elements are symmetrical
else return is_symmetrical_a( array+1, sz-2 ) ;
}
bool is_symmetrical_b( const int array[], std::size_t sz )
{
const int* begin = array ; // iterator to first item
const int* mid = array + sz/2 ; // iterator to middle
// reverse iterator starting at the last item
// https://en.cppreference.com/w/cpp/iterator/make_reverse_iterator
auto rbegin = std::make_reverse_iterator(array+sz) ;
// https://en.cppreference.com/w/cpp/algorithm/equal
return std::equal( begin, mid, rbegin ) ;
}
bool is_symmetrical_c( const int array[], std::size_t sz )
{
// https://en.cppreference.com/w/cpp/string/basic_string_view
std::basic_string_view<const int> view( array, sz ); // C+17
return std::equal( view.begin(), view.begin() + sz/2, view.rbegin() ) ;
}
int main()
{
const int a[] { 1, 2, 3, 4, 5, 4, 3, 2, 1 } ;
std::cout << std::boolalpha
<< is_symmetrical_a( a, std::size(a) ) << ' ' // true
<< is_symmetrical_b( a, std::size(a) ) << ' ' // true
<< is_symmetrical_c( a, std::size(a) ) << '\n' ; // true
const int b[] { 1, 2, 3, 4, 5, 4, 3, 4, 2, 1 } ;
std::cout << std::boolalpha
<< is_symmetrical_a( b, std::size(b) ) << ' ' // false
<< is_symmetrical_b( b, std::size(b) ) << ' ' // false
<< is_symmetrical_c( b, std::size(b) ) << '\n' ; // false
}
|