Word Length and Frequency 10293

This is an easy problem from uva judge http://uva.onlinejudge.org/external/102/10293.html

Ad hoc problem.

How I did it

  • Read line by line the strings while the first character of the string is diferent to # .
  • Iterate throught the string searching the characters that are alphabetics and saving the length of the current word.
  • If I find a space separator character (” ” ,? ,! ,. ,’,’) I save the current length of a word in a map<int, int> where the key is the size of the word and the value the number of word with the size of the key. Reset the word size variable.
  • If I find the # character as first character of a line, we print the map content.
  • Clean map, clear flag variables and print a blank line.

Hints

  • The input is small, a brute force aproach is enough.
  • The length of the word is only composed by alphabetic characters.
  • Consider this type of case as only a word:  you’ve  length = 5.
  • The space separators are: ” “, ?, !, ., , .
  • Print a blank line after each block.
  • And end block could be : #this is the end of block

Code

#include <iostream>
#include <cstdio>
#include <map>
#include <cctype>
using namespace std;
int main()
{
string cad;
map<int,int> myMap;
int wSize = 0;
while(getline(cin,cad))
{
    if(cad[0] != '#')
    {
        for(int a=0; a<cad.size(); a++)
        {
            if(isalpha(cad[a]))
               wSize++;
            else if(isspace(cad[a]) || cad[a] == '!' || cad[a] == '?' || cad[a] == ',' || cad[a] == '.')
            {
                myMap[wSize]++;
                wSize = 0;
            }
        }
        if(cad[cad.size()-1] != '-' && wSize>0)
        {
            myMap[wSize]++;
            wSize = 0;
        }
    }
    else
    {   map<int,int>::iterator it = myMap.begin();
        if(it->first == 0)
            it++;
        for(it = it; it!= myMap.end(); it++)
            printf("%d %d\n",it->first,it->second);
        printf("\n");
        wSize = 0;
        myMap.clear();
    }
}
return 0;
}

Leave a comment