我无法弄清楚如果有多个重复相同次数的ex,那么如何打印“无模式”。 5 5 6 6 7 6 9;由于5和6都重复了两次,所以我想打印出“无模式”,这是即时通讯用于查找模式的算法:

int mostfound = *pScores;
int most_found_count = 0;
int currentnum = *pScores;
int current_num_count = 0;
bool noMode = true;


//finding the mode
for (int i =  0; i < numScores; i++)
{
  if (*(pScores + i) == currentnum)
  {
     current_num_count++;
  }
  else {
      if (current_num_count > most_found_count)
        {
              mostfound = currentnum;
              most_found_count = current_num_count;
              noMode = false;

        }
  else if (current_num_count == most_found_count)
        {
            noMode = true;

        }

       currentnum = *(pScores + i);
       current_num_count = 1;
  }
}

cout << mostfound << endl;
        cout << currentnum << endl;
        cout << most_found_count << endl;

cout << "Mode: " << mostfound << endl;


}

最佳答案

std :: multiset可以帮助您

#include <set>
using namespace std;
....
multiset<int> setScores;
for (int i =  0; i < numScores; i++)
{
    setScores.insert(pScores[i]);
}
// setScores here got items = (a number being repeated)
// and count = (how many times number repeated)
multiset<int> setRepeats;
for (multiset<int>::iterator it = setScores.begin(); it!=setScores.end(); it++)
{
    setRepeats.insert(setScores.count(*it));
}
// setRepeats here got items = (how many times a number repeated)
// and count = (how many different numbers repeated this amount of times)
// Now search for count that > 1
noMode = false;
for (multiset<int>::iterator it1 = setRepeats.begin(); it1!=setRepeats.end(); it1++)
{
    if(setRepeats.count(*it1)>1)
    {
        noMode = true;
        break;
    }
}
// Now use noMode as you wish


PS请注意,示例数组中的数字6重复了3次,但是数字5仅重复了两次,因此noMode将为false

10-04 21:58
查看更多