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 <vector>
#include <string>
using namespace std;
//======================================================================
template<typename T> vector<T> mode( const vector<T> &A ) // Assumption: A already sorted
{
// Pass 1: find longest run
int longestRun = 1, currentRun = 1; // Corresponds to just A[0]
for ( int i = 1; i < A.size(); i++ )
{
currentRun = ( A[i] == A[i-1] ? currentRun + 1 : 1 );
if ( currentRun > longestRun ) longestRun = currentRun;
}
if ( longestRun == 1 ) return A; // Conveniently also deals with A being empty
// Pass 2: add anything with longest run to modes
vector<T> result;
currentRun = 1;
for ( int i = 1; i < A.size(); i++ )
{
currentRun = ( A[i] == A[i-1] ? currentRun + 1 : 1 );
if ( currentRun == longestRun ) result.push_back( A[i] );
}
return result;
}
//======================================================================
int main()
{
vector< vector<int> > test = { {},
{ 1 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 2, 4, 4, 6, 8 },
{ 1, 2, 3, 4, 4, 5, 5, 5, 7, 8, 9 } };
// vector< vector<double> > test = { { 3.4, 4.5, 4.5, 6.0, 9.0 , 9.0, 11.0 },
// { 1.0, 5.5, 5.5, 5.5, 7.3 } };
// vector< vector<string> > test = { { "bus", "car", "car", "car", "rocket", "train", "train", "train" } };
for ( const auto &A : test )
{
cout << "Array: "; for ( auto e : A ) cout << e << ' ';
cout << '\n';
cout << "Modes: "; for ( auto e : mode( A ) ) cout << e << ' ';
cout << "\n\n";
}
}
|