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

Write a programme using structure that create a record of students. The user allow to add a record and delete a record and also show the records in ascending order.

1620


Is main a keyword in c?

632


Write a program to print fibonacci series without using recursion?

610


Why isn't it being handled properly?

645


Explain what is a program flowchart and explain how does it help in writing a program?

649






What is atoi and atof in c?

618


What is meant by type casting?

629


What is an auto variable in c?

758


Why cant I open a file by its explicit path?

593


What is scope rule in c?

606


5 Write an Algorithm to find the maximum and minimum items in a set of ā€˜nā€™ element.

1582


void main(int n) { if(n==0) return; main(--n); printf("%d ",n); getch(); } how it work and what will be its output...............it any one know ans plz reply

2226


Do you know the purpose of 'register' keyword?

642


Write a C/C++ program to add a user to MySQL. The user should be permitted to only "INSERT" into the given database.

1497


How can I implement a delay, or time a users response, with sub-second resolution?

625