2017-04-18 2 views
-1
//Code for Character Count 
#include <iostream> 
#include <string.h> 
#include <vector> 

std::vector <char> s_character; 
std::vector <int> count_occurence; 


/*Function to check occurence of a character in the character vector, 
if found return position, 
else return -1 indicating no occurence 
*/ 

int check_character_occurence(char character) 
{ 
    for (int i=0;i<s_character.size();i++) 
    { 
     if(s_character.at(i)==character) 
      return i; 
    }  

    return -1; 

}//end_of_check_character_occurence_function 


/*Function to do the counting of individual characters, 
if character is not present(occuring for the first time) then add to both character vector and count vector 
else update count at position 
*/ 

void count_algorithm(char character) 
{ 
    int pos_flag; 

    pos_flag = check_character_occurence(character); 

    if (pos_flag==-1) 
    { 
     s_character.push_back(character); 
     count_occurence.push_back(1); 
    } 

    else 
     count_occurence.at(pos_flag)++; 

}//end_of_count_algorithm_function 


int main() 
{ 
    std::string sequence; 
    char separated_character; 

    std::cout<<"\nEnter String: "; 
    std::cin>>sequence; 
    std::cout<<"\nLength is "<<sequence.length()<<" characters."; 

    for(int i=0; i<sequence.length(); i++) 
    { 
     separated_character=sequence[i]; 
     count_algorithm(separated_character); 
    } 

    for(int i=0;i < s_character.size(); i++) 
     std::cout<<"\nCharacter: "<<s_character[i]<<" Occurence: "<<count_occurence[i]; 

    return 0; 

}//end_of_main_code 

私はDNA配列サンプルを取った。文字カウントのコードを書いています。このC++コードを最適化する方法はありますか(時間、空間の複雑さなど)

出力:

は、文字列を入力します。AGCTAGCATCGTGTCGCCCGTCTAGCATACGCATGATCGACTGTCAGCTAGTCAGACTAGTCGATCGATGTG

長は72文字です。

キャラクター:出現:16

キャラクター:G出現:19

キャラクター:C出現:19

キャラクター:T出現:18

+1

あなたが解決しようとしている問題は何ですか? –

+0

あなたの研究/デバッグの努力をこれまでのところ表示してください。まず[Ask]ページをお読みください。 –

+0

私はそれがより速く実行できるかどうかを意味します。 –

答えて

1

両方の遭遇する文字を記憶していますベクトルのカウンタを動的にサイズ変更し、毎回すべての要素を反復して検索を実行します。文字の総数は分かっています(256と仮定します)。したがって、カウンターを配列として宣言し、charでインデックスすることができます。

std::array< int, 256 > counters{}; 
for(int i=0; i<sequence.length(); ++i) 
{ 
    ++counters[sequence[i]]; 
} 
+0

サイズを256文字に固定してもスペースが複雑にならないでしょうか?別の文字が少なく、出現頻度が低い場合は意味します。 –

+0

いいえ。最終的には、とにかく同じ256文字をベクトルに割り当てる必要があります(指定された入力文字列は十分に変化します)。実際に配列を持つことは、もはやベクトルを必要としないので空間の複雑さを減らします。 – VTT

+0

@PlabanBiswas&VTT漸近的な空間の複雑さはいずれの方法でも変わらない。それは一定のままです。 (時間の複雑さは変わらない、それは線形のままである) – user2079303

関連する問題