Write the program for displaying the ten most frequent words
in a file such that your program should be efficient in all
complexity measures.
Answers were Sorted based on User's Feedback
Answer / rob lange
Here ya go... It's not pretty...
#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <algorithm>
using namespace std;
int main()
{
string line, file;
stdext::hash_map <std::string, int> words;
stdext::hash_map <std::string, int>::iterator wordsit;
ifstream myfile("example.txt");
// Load file into string
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline(myfile,line);
file.append( line );
file.append( " " );
}
myfile.close();
}
// Parse words into hashmap
char * threadsafe;
char * token = strtok_s((char*)file.c_str(), " ", &threadsafe);
while (token != NULL)
{
wordsit = words.find(token);
if (wordsit != words.end())
++wordsit->second;
else
words[token] = 1;
token = strtok_s(NULL, " ", &threadsafe);
}
// find top 10 threshold value
std::vector < int > topvalue;
int threshold = 0;
for ( wordsit = words.begin(); wordsit != words.end();
wordsit++ )
{
topvalue.push_back( wordsit->second );
}
sort( topvalue.begin(), topvalue.end() );
reverse( topvalue.begin(), topvalue.end() );
if ( topvalue.size() > 10 )
threshold = topvalue[9];
// Search hashmap against value and print word if its
within top10 threshold...
// ties also get printed, so the list might be longer than 10
for ( wordsit = words.begin(); wordsit != words.end();
wordsit++ )
{
if( wordsit->second >= threshold )
cout << wordsit->first << endl;
}
return 0;
}
Is This Answer Correct ? | 5 Yes | 4 No |
Answer / mayank maheshwari
Hi,
you can do it in a cleaner way using STL map and getting rid
of all the messy strtok() functions. Just writing how to
construct the map. The idea of putting into a vector and
sorting can still work.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
int main(int argc,char*argv[])
{
string word;
map <string, int> freq;
map <string, int>::const_iterator wordsit;
fstream myfile;
myfile.open(argv[1],ios::in);
// Load file into string
if (myfile.is_open())
{
while (myfile >> word)
{ freq[word]++;
}
myfile.close();
}
//To see the map created
for (wordsit=freq.begin();wordsit!=freq.end();wordsit++)
{cout<<"Key: "<<wordsit->first<<"Value:
"<<wordsit->second<<endl;
}
Is This Answer Correct ? | 3 Yes | 5 No |
What should malloc(0) do? Return a null pointer or a pointer to 0 bytes?
Is fortran faster than c?
Explain spaghetti programming?
What is the difference between malloc() and calloc()?
What is pass by reference in c?
can we access one file to one directory?
Are pointers integer?
What is dynamic memory allocation?
Which is the memory area not included in C program? give the reason
what do structure language means?
how should functions be apportioned among source files?
explain what is an endless loop?