c++ - 寻找模式 C++

标签 c++ math computer-science mode

如何编辑此函数以查找多种模式?现在如果有多个,它会显示最小的。

例子

输入 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;
}

任何帮助!

最佳答案

我也喜欢其中一条评论提到的 stdlib 选项。但是,我试图在不像您那样使用它的情况下解决这个问题(作为练习)。我曾要求有一个常量数组作为函数参数,所以我无法订购它(既没有删除常量也没有将它复制到一个新的非常量数组中).此外,如果有多种模式或没有元素,我必须返回零

最后 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;
}

感谢您的关注!

关于c++ - 寻找模式 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43004792/

相关文章:

c++ - 错误 : no matching member function for call to 'reset' (shared pointers)

c++ - 从一个类到任何类的成员函数的函数指针

javascript - 随机放置矩形,但不在中心 x 半径范围内

algorithm - 随机生成一组长度为 n 的数字,总计 x

javascript - 我如何在一页上使用两个 javascript 幻灯片?网页格式

nosql - 简单英语的最终一致性

java - NDK : Does GetByteArrayElements copy data from Java to C++?

c++ - 如何为不允许修改数据的 shared_ptrs 容器编写 getter

ruby - 两个运算符(+,-)对数组项的所有可能操作

c - 访问冲突写入位置 c ,二维动态数组