I need to write a function that would get a copy of an array and go through it to see which of the below conditions is satisfied by that array. function prototype is this :
unsigned g( const unsigned a[], unsigned elements );
No I/O. g returns a code in the range [0, 8) according to the data in a:
0: elements < 2, so no element has a predecessor.
e.g. {}
e.g. {1234}
1: elements >= 2, and every element is < its predecessor.
e.g. {10, 9, 2}
2: elements >= 2, and all the elements are equal.
e.g. {8, 8, 8, 8}
3: at least one element is < its predecessor, at least one element is == its predecessor, but no element is > its predecessor.
e.g. {10, 10, 8, 8, 5, 5, 5, 5, 3}
4: elements >= 2, and every element is > its predecessor.
e.g. {2, 4, 8, 16}
5: at least one element is < its predecessor, at least one element is > its predecessor, but no element is == its predecessor.
e.g. {3, 2, 3, 4}
6: at least one element is == its predecessor, at least one element is > its predecessor, but no elements is < its predecessor.
e.g. {5, 5, 10, 20}
7: at least one element is < its predecessor, at least one element is == its predecessor, and at least one element is > its predecessor.
e.g. {5, 4, 5, 5}
If I haven’t made a mistake, you should be able to convince yourself that every array will fall into exactly one of these 8 categories. g’s job is to return the number of that category.
For instance, g( {5, 4, 5, 5} should return 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
unsigned g( const unsigned a[], unsigned elements )
{
if ( elements < 2 ) return ( 0 );
enum { LT, EQ, GT };
unsigned int count[3] = {};
std::inner_product ( a, a + elements - 1, a + 1, count,
[]( unsigned int *p, unsigned int i ) { return ( ++p[i], p ); },
[]( int x, int y ) { return ( x < y ? LT : ( x == y ? EQ : GT ) ); } );
if ( count[LT] == elements - 1 ) return ( 1 );
else if ( count[EQ] == elements - 1 ) return ( 2 );
else if ( count[LT] && count[EQ] && !count[GT] ) return ( 3 );
else if ( count[LT] && count[EQ] && count[GT] ) return ( 7 );
else throw ( die( "Unpredictable result." ) );
|
I'm getting compiler error in std::inner_product part. Any solution or substitution?