如果多次重复相同的次数,我需要输出“无模式”

时间:2014-01-22 05:20:13

标签: c++ arrays pointers

如果有多个号码重复相同的次数,我就无法弄清楚如何打印“无模式”。 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;

}

1 个答案:

答案 0 :(得分:0)

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