Mrowkacala Mrowkacala - 10 days ago 5
C++ Question

Function that counts unique characters in an array

I want to have a function that counts number of unique characters. If for example i have

aabbcc
i want it to return
3
. If
aab
i want to have
2
and so on....

My attempt was to construct a function that is checking whether number appeared previously and then us it as
if
condition.

My code is:

bool firstocc(char* t, int i){
for(int j = 0;j < i;j++){
if(t[j] == t[i]) return false;
return true;
}
}

int h(char* t){
int c=0;
for(int i=0; t[i+1]!=0;i++){
if(firstocc(t,i)){
c++;
}

return c;
}

}


int main()
{
cout<< h("aabbc");
}


Function always returns zero. What is wrong with it?

Answer

The problem was with the braces in both functions firstocc and h (maybe because a bad indentation, always try take care with indent your code properly, not for compiler but for yourself), and with the loop of function h where the condition was t[i+1] != 0 and should be t[i] != 0 (to include the last char).

The code should be:

bool firstocc(char* t, int i){
    for(int j=0;j<i;j++)
        if(t[j]==t[i])
            return false;
    return true;
}

int h(char* t){
    int c=0;
    for(int i=0; t[i]!=0;i++)
        if(firstocc(t,i)){
            c++;
        }
    return c;
}

I tested it with "aabbcddddeaa" and it returns 5.

Comments