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 <algorithm>
#include <map>
using namespace std;
using codeType = int;
using Vec = vector<codeType>;
using Vec2D = vector<Vec>;
using PR = pair<codeType,int>;
bool sortOrder( PR a, PR b )
{
if ( a.second == b.second ) return a.first < b.first; // If equal frequencies, then in ascending order of maint code
return a.second > b.second; // Otherwise, descending order of frequency
}
int main ()
{
Vec2D mcvec { {2, 9, 12, 14},
{1, 7, 9, 16},
{2, 8, 10, 17}, // Start Counting mcvec[2].begin()
{3, 7, 11, 15},
{1, 10, 14, 15},
{4, 5, 12, 17},
{1, 9, 15, 17},
{4, 11, 15, 16},
{2, 10, 12, 14},
{4, 7, 11, 12}, // End Counting mcvec[9].end()
{2, 5, 11, 15} };
// Generate frequency distribution
map<codeType,int> freq;
for ( codeType e = 1; e <= 17; e++ ) freq[e] = 0;
for ( int row = 2; row < 10; row++ )
{
for ( auto e : mcvec[row] ) freq[e]++;
}
// Reassemble in linear data structure
vector<PR> maintFreq( freq.begin(), freq.end() );
cout << "Original counts:\n";
for ( PR pr : maintFreq ) cout << pr.first << ": " << pr.second << '\n';
// Sort
cout << "\nSorted by frequency (descending), then maintenance code (ascending):\n";
sort( maintFreq.begin(), maintFreq.end(), sortOrder );
for ( PR pr : maintFreq ) cout << pr.first << ": " << pr.second << '\n';
}
|