tags:

views:

74

answers:

2

Can you give me some hint on how to calculate if there are two or more modes in c?

I was able to create a program that will calculate for the mode, but if i have a dataset with multiple modes, like 5,3,1,2,3,4,6,4 my program only finds 3 as a mode, rather than both 3 and 4.

+3  A: 

An approach might go something like this:

  1. Determine how many times each value appears, keep a list
  2. Determine the maximum number of times any value appears (by looking at your list)
  3. Find all values that appear the maximum number of times (by looking at your list)
Mark E
thank you very much:) i got it",
A: 

Just realized that you're restricted to C.. guess this answer doesn't work then.

This should do what you want (I think.. I've not tried it).

std::vector<int> calculateModes(std::vector<int> input)
{
    std::sort(input.begin(), input.end());
    std::vector<int> modes;
    int lastModeCount = 0;
    std::vector<int>::const_iterator cursor = input.begin();
    while(cursor < input.end())
    {
        std::vector<int>::const_iterator endOfRun
            = std::find_if(cursor, input.end(),
            std::not1(std::bind2nd(std::equal_to<int>(), *cursor)));
        int modeCount = std::distance(cursor, endOfRun);
        if (modeCount > lastModeCount)
        {
            modes.clear();
            modes.push_back(*cursor);
        }
        else if (modeCount == lastModeCount)
            modes.push_back(*cursor);
        cursor = endOfRun + 1;
    }
    return modes;
}
Billy ONeal