Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <vector>
- #include <algorithm>
- using namespace std;
- vector<int> modeVect(vector<int>& vect);
- int main()
- {
- vector<int> values; //vector of ints generated by user input
- int num; //number added to vector
- char again; //continue entering values to the vector
- cout << "\nThis program will find the mode(s) of a list given by you." << endl;
- do
- {
- cout << "Please enter an integer to add to the list: ";
- while(!(cin >> num))
- {
- cin.clear();
- cin.ignore(256, '\n');
- cout << "ERROR\n";
- cout << "Please enter a valid integer to add to the list: ";
- }
- values.push_back(num);
- cout << "Would you like to add another integer to the list? (Y/N): ";
- cin >> again;
- }while (again == 'Y' || again == 'y');
- vector<int> mode(modeVect(values));
- cout << "\n\nThe mode(s) calculated: ";
- for(int i =0; i < mode.size(); i++)
- {
- cout << mode[i] << " ";
- }
- cout << "\n\n";
- return 0;
- }
- vector<int> modeVect (vector<int>& vect)
- {
- sort(vect.begin(), vect.end());
- int current; //current number being tallied
- int count = 0; //iteration
- int old_freq = 0; //compare to older mode
- vector<int> mode;
- do{
- int frequency = 0; //frequency a number appears
- current = vect[count];
- for(int i = 0; i < vect.size(); i++)
- {
- if(vect[i] > current)
- break;
- if(vect[i] == current)
- {
- frequency++;
- }
- }
- if(frequency == old_freq)
- {
- for(int j = 0; j < mode.size(); j++)
- {
- if(mode[j] == current)
- goto same;
- }
- mode.push_back(current);
- }
- if(frequency > old_freq)
- {
- mode.clear();
- mode.push_back(current);
- old_freq = frequency;
- }
- same:
- count++;
- }while (count < vect.size());
- return mode;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement