Search code examples
c++mode

finding multiple modes from a vector of doubles


So we were asked to get the mode(s) for a vector that the user is going to fill in, it is a vector of doubles, so far i got it working for getting 1 mode, but when it comes to more than 1 mode i freeze, anyone got any suggestions ?(btw im a beginner with coding so don't roast )

void getMode(vector<double> v)
{
    double element = 0;
    int freq = 0;

    for (int it = 0; it != v.size(); it++)
    {
        double tempElement = v[it];
        int tempFreq = 0;
        for (int i = 0; i < v.size(); i++)
            if (v[i] == tempElement)
                tempFreq++;
        if (tempFreq > freq)
        {
            element = tempElement;
            freq = tempFreq;
        }
     }

    if(freq > 1 )
    { 
        cout << "\nfreq: " << freq <<"\nElement: " << element;
    }
    else
    {
        cout << "\nno mode ";
    }
} 

so lets say the user inputs 1,1,3,3,4,5 my mode will be only the number 1 instead of 1 and 3, it basically takes the first mode it finds and prints it instead of printing both modes i got.


Solution

  • Here is another example using unordered_map to count the frequencies:

    #include <algorithm>
    #include <iostream>
    #include <vector>
    #include <unordered_map> 
    using namespace std;
    
    bool compareFreq(const pair<double,int> &p1, const pair<double,int> &p2) 
    { 
        return (p1.second > p2.second); 
    }
    
    void getMode(const vector<double> &v)
    {
        unordered_map<double,int> freq_map;
        for (auto elem : v) {
            freq_map[elem]++;
        }
        vector<pair<double,int>> freq_vec(freq_map.begin(), freq_map.end());
        sort(freq_vec.begin(), freq_vec.end(), compareFreq);
        for (auto elem : freq_vec ) {
            cout << elem.first << " : " << elem.second << endl;
        }     
    }
    
    int main()
    {
        vector<double> v {1.0, 2.0, 1.0, 3.0, 4.0, 3.0, 3.0};
    
        getMode(v);
    
        return 0;
    }
    

    Output:

    3 : 3
    1 : 2
    4 : 1
    2 : 1