2014-01-22 25 views
1

如果有多於一個數字重複相同的次數,我不知道如何打印「無模式」恩。 5 5 6 6 7 6 9;因爲5和6都重複兩次,我想打印出「無模式」在這裏是用來尋找模式的算法IM:如果不止一個數字重複相同次數,我需要輸出「無模式」

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

的std ::多集可以幫助你

#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將爲假

+0

也許他是連續的意思? –

+0

也許,「連續」可以將任務納入他的結果。如果是這樣,那麼我的代碼就是一個垃圾,算法必須完全重寫 –

相關問題