1

你能给我一些关于如何计算c中是否有两种或多种模式的提示吗?

我能够创建一个计算模式的程序,但是如果我有一个具有多种模式的数据集,比如5,3,1,2,3,4,6,4我的程序只找到 3 作为模式,而不是 3 和 4。

4

2 回答 2

3

一种方法可能是这样的:

  1. 确定每个值出现多少次,保留一个列表
  2. 确定任何值出现的最大次数(通过查看您的列表)
  3. 查找出现次数最多的所有值(通过查看您的列表)
于 2010-02-20T05:52:36.320 回答
0

刚刚意识到您仅限于 C.. 猜猜这个答案不起作用。

这应该做你想做的(我认为..我没有尝试过)。

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;
}
于 2010-02-20T05:59:10.930 回答