如何编辑此函数以查找多种模式?现在如果有多个,它会显示最小的。
例子
输入 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/