Counting not equal strings in array in C++

Viewed 346

I want to count all the different string elements in an array. So my input would be:

5 Lemon Orange Lemon Mango Lemon

And the output should be this:

3

The problem with my code is, that my code counts all the elements, and not just the different and I can't figure out why.

Here is my code:

#include <iostream>

using namespace std;

int main()
{
    int N;   
    cin >> N;
    string Tname;
    string data[N];
    int counter = 0;

    for(int i = 0; i<N; i++)
    {
        cin >> Tname;
        data[i] = Tname;
    }

    for(int l = 0; l<N; l++)
    {
        int k = 0;
        while(k<N && (data[l] != data[k]))
        {
            k++;
        }
        if(k<N)
        {
            counter += 1;
        }

    }
    cout << counter << endl;
    return 0;
}
3 Answers

The problem is algorithmic: every item is equal to itself, which will end your k loop prematurely. In addition, you only increment when the item is repeated.

I propose you to change the loops, so not to compare every items with every other items, but only items, to items previously processed:

for(int l = 0; l<N; l++)
{
    int k = 0;
    while(k<l &&  data[l] != data[k])  // only previous items
    {
        k++;
    }
    if(k==l)   // if no identical, we can add this one
    {
        cout<<l<<" "<<data[l]<<endl;
        counter += 1;
    }
}

Not related: variable length arrays are not legal C++ even if some mainstream compilers accept it. I'd suggest to use a vector to emulate this feature: vector<string> data(N);

Online demo

if i understand well your problem , you want the value that has the max appearances in the array, some modifications are needed to achieve this :

#include <iostream>

using namespace std;

int main()
{
    int N;   
    cin >> N;
    string Tname;
    string data[N];
    int counter = 0;

    for(int i = 0; i<N; i++)
    {
        cin >> Tname;
        data[i] = Tname;
    }

    int tempCounter; // a temporary counter for each item of the array .
    for(int l = 0; l < N; l++)
    {
        tempCounter = 0;
        int k = 0;
        while(k<N)
        {
            if(data[l] == data[k])
                tempCounter++;
            k++;
        }
        if(tempCounter > counter) // if the new counter is higher than the counter 
            counter = tempCounter;
    }
    cout << counter << endl;
    return 0;
}

the last if should be if(k+1==N)

because you all the time stop the while before the k reach N

and k must start from l

Your logic is, you add 1 to the counter if it is not in the list's remaining part But the code check the full list so you never count thw world whitch in the list twice.

Related