Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max frequency of character in string

Tags:

c++

string

#include<bits/stdc++.h>
#include<cstring>
#define arraySize 10

using namespace std;
char returnMaxOccur(char *str);

int main()
{
    char str[]="teet";
    cout<<"The max occuring character is"<<" "<<returnMaxOccur(str)<<endl;
    return 0;
}

char returnMaxOccur(char* str)
{
    int high=-1;
    char t;
    int counter[arraySize]={0};

    int len=strlen(str);

    for(int i=0;i<len;i++)
    {
        counter[str[i]]++;
    }


    for(int i=0;i<len;i++)
    {
        if(high<counter[str[i]])
        {
            high=counter[str[i]];
            t=str[i];
        }
    }
    return t;
}

In the following question when #include<bits/stdc++.h> is included the results for input string are as follows,

1)teet: ans is t  
2)eett: ans is e  
3)ttee: ans is t  
4)ette: ans is e  

but when i include #include<iostream> instead of #include<bits/stdc++.h> the results are

1)teet: ans is e  
2)eett: ans is t  
3)ttee: ans is t  
4)ette: ans is e  

what is the reason for this behaviour,or am i doing anything wrong?

like image 949
SU15 Avatar asked Mar 09 '23 01:03

SU15


2 Answers

This is a textbook case of how undefined behaviour can manifest in seemingly bizarre behaviour.

In practice, including different headers has likely affected what bytes are at certain positions in memory, bytes that you accidentally observe when you vastly overrun your array counter (size 10) with indexes that could go all the way up to 255.

The traditional way to approach this task is with a std::map<char, int>, which can effectively function as a "sparse array". Failing that, just make sure you have enough "slots" in your int[] for every possible input.

(And, IMO, you shouldn't be using bits/stdc++.h anyway.)

like image 101
Lightness Races in Orbit Avatar answered Mar 12 '23 00:03

Lightness Races in Orbit


The first important thing is that your code is not correct. Please correct it as follows:

Instead of

#define arraySize 10

use

#define arraySize 128

as str[i] may be arbitrary character (I suppose an ASCII character from 0 to 127)

and only then repeat your testing with changing the #include statement.

The second - and generally more important - was just expressed by πάντα ῥεῖ in his link (Why should I not #include ?)

like image 32
MarianD Avatar answered Mar 12 '23 01:03

MarianD