查找模式C ++

问题描述 投票:1回答:1

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

示例

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

任何帮助!

c++ math computer-science mode
1个回答
0
投票

我也喜欢stdlib选项,其中之一是注释。但是,我尝试不使用它(作为练习)来解决此问题。我必须要有一个constant array作为函数参数,所以我无法排序(不要删除常量,也不能将其复制到新的非常量变量中)。另外,如果有多个模式或没有元素,则必须返回零

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

#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;
}

感谢您的关注!

© www.soinside.com 2019 - 2024. All rights reserved.