【问题标题】:i need to output "no mode" if more than one number is repeated the same amount of times如果多个数字重复相同的次数,我需要输出“无模式”
【发布时间】:2014-01-22 05:20:13
【问题描述】:

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

}

【问题讨论】:

  • 虽然通过地图可以很容易地计算出出现的频率,但是对于这个特定的代码,如果你解释一下你的算法会有所帮助。

标签: c++ arrays pointers


【解决方案1】:

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

【讨论】:

  • 也许他的意思是连续的?
  • 也许,“连续”可以使任务适合他的结果。如果是这样,我的代码就是垃圾,那么算法必须完全重写
猜你喜欢
  • 1970-01-01
  • 2014-06-17
  • 2018-06-18
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多