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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <vector>
double values[] =
{
1.0, 1.0,
2.0, 2.0,
3.0, 3.0, 3.0,
4.0, 4.0, 4.0, 4.0, 4.0,
5.0, 5.0, 5.0, 5.0, 5.0,
6.0, 6.0, 6.0, 6.0,
};
typedef std::vector<double> vec_type ;
vec_type getMode( const vec_type& v ) ;
void print( const char* msg, const vec_type& v ) ;
int main()
{
vec_type v(values, values+sizeof(values)/sizeof(values[0])) ;
print("Modes", getMode(v)) ;
}
// PRE: v.empty() != true; v is sorted.
// POST: a non-empty vector of distinct modal values is returned.
vec_type getMode( const vec_type& v )
{
vec_type modes ;
vec_type::const_iterator it = v.begin() ;
double runValue = *it++ ;
unsigned runCount = 1 ;
unsigned highestRunCount = runCount ;
modes.push_back(runValue) ;
while ( it != v.end() )
{
if ( runValue == *it ) // run continuing.
{
if ( ++runCount > highestRunCount ) // current run is new high?
{
highestRunCount = runCount ;
if ( modes.front() != runValue ) // then there should only be one mode
{
modes.clear() ;
modes.push_back(runValue) ;
}
}
else if ( runCount == highestRunCount ) // more than one mode, currently
modes.push_back(runValue) ;
}
else // new run beginning
runValue = *it, runCount = 0 ;
++it ;
}
return modes ;
}
void print( const char* msg, const vec_type& v)
{
std::cout << msg << '\n' ;
for ( vec_type::const_iterator it = v.begin(); it != v.end(); ++it )
std::cout << *it << '\t' ;
std::cout << '\n' ;
}
|