Write the program for displaying the ten most frequent words
in a file such that your program should be efficient in all
complexity measures.

Answer Posted / 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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Create a structure to specify data on students given below: Roll number, Name, Department, Course, Year of joining Assume that there are not more than 450 students in the college. 1.write a function to print names of all students who joined in a particular year 2.write a function to print the data of a student whose roll number is given

2525


Explain why C language is procedural?

775


please explain clearly about execution of c program in detail,in which stage are the printf sacnf getting into exeecutable code

1712


Is the exit() function same as the return statement? Explain.

668


What are the ways to a null pointer can use in c programming language?

593






write a proram to reverse the string using switch case?

2474


Explain what is the difference between functions abs() and fabs()?

628


main() { inta=10,b=20; a>=5?b=100:b=200; printf("%d ",b); }

917


What is difference between array and pointer in c?

542


Are the outer parentheses in return statements really optional?

581


Is return a keyword in c?

603


What is a macro in c preprocessor?

636


What is union and structure in c?

623


What are different storage class specifiers in c?

623


Which type of language is c?

656