Search code examples
c++vectormapsmode

Finding multi modes in a vector using maps


So I've been at this mode thing for a while, and got some help figuring out just how to do it on here and thought I might ask for a little more assitance. I've got this much figured out.

map<int,unsigned> frequencyCount;
//This is my attempt to increment the values of the map everytime one of the same numebers 
for(size_t i = 0; i < v.size(); ++i)
    frequencyCount[v[i]]++;

unsigned currentMax = 0;
unsigned checked = 0;
unsigned mode = 0;
for(auto it = frequencyCount.cbegin();
    it != frequencyCount.cend(); ++it )

if (it ->second > currentMax)
    {
        mode = it->first;
        currentMax = it->second;
    }

if (currentMax == 1)
{
    cout << "There is no mode in the vector" << endl;
}

else {
cout << " The mode of the vector is: " << mode << endl;
}

}

So it will reutrn the most frequently occuring int within the vector, and return that there is no mode if the none of the map values exceed 1. Now I've been trying to figure out what to in the case of more than one mode, ex. 1 2 3 3 4 4 5 currently returns 3. I would like to reutrn 3 and 4.

Logically I would say an if statement checking the variable which occurs most frequently against the second most frequent would work. Of course there is the possibility of 400 modes if the test data is large enough though. So I would need to create a loop the goes through checking and exits when the current variable is no longer equal to the one that occurs one less frequently than it. I'm just really not sure how to go about that. Any advice on where to get started?


Solution

  • As you point out, the mode is not necessarily unique.

    So, you should supply the answer as a set of numbers, as you've correctly stated.

    I would create a vector to store the set of unique modes from your set, then output the content of the mode vector.

    e.g.

    std::vector<float> Modes;
    
    // 3 is detected as mode as it occurs 3 times in your set
    Modes.push_back(3);
    
    // 4 is also detected as mode, since it also occurs 3 times in your set
    Modes.push_back(4);
    
    // output the modes for the set
    std::cout << "the following mode(s) were detected in the set";
    for( int n = 0; n < Modes.size(); n ++ )
    {
      std::cout << "Mode: " << Modes[n] << "\n";
    }
    

    hope this makes sense