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
|
// Find the min, max, and mode of a string
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}
void stringtest(vector<string> &storage, string &mode, string &max,
string &min, int maxfreq, string x){
sort(storage.begin(),storage.end());
int freq = 0;
/*
* Careful with array indexes, they start @ 0
* reading beyond the top index will produce
* an exception error (Segmentation Fault)
* and your code will crash.
*/
for(unsigned int i = 1; i <= storage.size(); i++){
if (x == storage[i-1]){
if (++freq > maxfreq){
maxfreq = freq;
mode = x;
}
}
}
// indexes again.
max = storage[storage.size()-1];
min = storage[0];
cout << "\n";
cout << "Mode is " << mode << endl;
cout << "Max is " << max << endl;
cout << "Min is " << min << endl;
}
int main() {
int maxfreq = 0;
string input, mode, max, min;
string yesno;
vector<string>storage;
while(true){
cin.ignore();
cin >> input;
//getline(cin, input); // use this instead of cin if you want to get a full line rather than the first word.
storage.push_back(input);
stringtest(storage, mode, max, min, maxfreq, input);
cout << "Contine? Y/N" << endl;
cin >> yesno;
if (yesno == "Y"){
continue;
}
else if (yesno == "N"){
break;
}
}
return 0;
}
| |