XNA
XNA

Reputation: 11

Finding the most occuring character in an array of char

I'm trying to find the most occurring character in this array with the following algorithm:

char a[]={"aaaadddddaa"};
int max=0;
int count=0;
char maxCharcter;
for(char q='a';q<='z';q++)
{
    for(int i=0; i<strlen(a);i++)
    {
        if(a[i]==q)
            count++;
    }

    if(count>max)
    {
        max=count;
        maxCharcter=q;
    }
}

cout<<max<<endl;
cout<<maxCharcter<<endl;

The output should have been max=6 maxCharcter=a, but I get max=11 maxCharcter=d. What am I doing wrong?

Upvotes: 1

Views: 3020

Answers (2)

Christian Stieber
Christian Stieber

Reputation: 12496

That's probably you only "reset" count once, not for every character.

int count=0;
char maxCharcter;
for(char q='a';q<='z';q++)
{
    for(int i=0; i<strlen(a);i++)

Probably should be

char maxCharcter;
for(char q='a';q<='z';q++)
{
    int count=0;
    for(int i=0; i<strlen(a);i++)

Other than that, you could speed up the whole thing by just going through the string once, using another array to count the occurrences of each char...

Upvotes: 1

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

count should be initialized inside your first for loop

for(char q='a';q<='z';q++) {
   count = 0;
   //continue code here
}

Upvotes: 1

Related Questions