【问题标题】:Finding the Mode C++寻找模式 C++
【发布时间】:2017-08-17 16:54:07
【问题描述】:

如何编辑此功能以查找多种模式?现在如果有多个,它将​​显示最小的。

例子

输入 5 5 2 2 输出 5 2

它实际上做了什么

输入 5 5 1 1 输出 1

void calculateMode(int array[], int big)
{

    int counter = 1;
    int max = 0;
    int mode = array[0];
    for (int pass = 0; pass < big - 1; pass++)
    {
       if ( array[pass] == array[pass+1] )
       {
          counter++;
          if ( counter > max )
          {
              max = counter;
              mode = array[pass];
          }
       } else
          counter = 1; // reset counter.
    }
cout << "The mode is: " << mode << endl;
}

任何帮助!

【问题讨论】:

  • 如果赋值允许使用标准库,考虑使用std::map&lt;int,int&gt; freq;创建一个整数到你看到它的次数的映射:freq[array[pass]]++然后查看freq为最高计数。如果没有,那么您最好的选择是学习如何使用几乎可以肯定随您的开发环境附带的调试软件。一旦您开始逐行执行代码,您很快就会发现自己的错误。
  • Algorithm to compute mode 的可能重复项 ... Dietmar Kühl 的回答与您在这里尝试做的非常接近。

标签: c++ math computer-science mode


【解决方案1】:

我也喜欢其中一个 cmets 所指的 stdlib 选项。但是,我尝试在不使用它的情况下解决这个问题(作为练习)。我要求有一个 constant array 作为函数参数,所以我不能订购它(也不能删除常量,也不能将它复制到一个新的非常量中)。此外,如果有多种模式或没有元素,我必须返回零

最后,a 想出了类似以下的内容。希望它可能会有所帮助。

#include <iostream>
#include <stdexcept>

template <typename T> T mode(const T *values, size_t length) {

  // check if it has zero length
  if (!length)
    return 0;

  if (!values)
    throw std::invalid_argument{"Invalid input array"};

  int count{}, maxOccurrences{};
  int multipleModes{};
  T mode{};

  // check every element unless the mode's occurrences are greater than the
  // remaining list
  for (int k{}; k < length && maxOccurrences <= (length - k); ++k) {

    // reset the count for every individual element
    count = 0;

    // count the number of occurrences
    for (int i{}; i < length; ++i) {
      if (values[k] == values[i])
        count++;
    }

    if (count > maxOccurrences && mode != values[k]) {
      mode = values[k];
      maxOccurrences = count;
      multipleModes = 0;
      /*std::cout << "Count:" << count << " - MaxOccur:" << maxOccurrences
                << " - Mode:" << mode << std::endl;*/
    }

    if (count == maxOccurrences && mode != values[k]) {
      // if the array has multiple modes
      multipleModes = 1;
    }
  }

  if (multipleModes == 1)
    return 0;
  else
    return mode;
}

感谢您的关注!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 2014-12-29
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多