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
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
Explain why C language is procedural?
please explain clearly about execution of c program in detail,in which stage are the printf sacnf getting into exeecutable code
Is the exit() function same as the return statement? Explain.
What are the ways to a null pointer can use in c programming language?
write a proram to reverse the string using switch case?
Explain what is the difference between functions abs() and fabs()?
main() { inta=10,b=20; a>=5?b=100:b=200; printf("%d ",b); }
What is difference between array and pointer in c?
Are the outer parentheses in return statements really optional?
Is return a keyword in c?
What is a macro in c preprocessor?
What is union and structure in c?
What are different storage class specifiers in c?
Which type of language is c?