Created
February 23, 2017 11:11
-
-
Save yhaskell/093c44917348cf99f158611a0f4c3cd8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Word list by frequency | |
Written by Igor N. Dultsev | |
Tested to compile by Visual C++ Compiler version 19.10.24903.0 (x86) with no additional keys | |
For compilation with g++, use the following command: g++ -std=c++14 word-freq-list.cc | |
*/ | |
#include <iostream> | |
#include <map> | |
#include <vector> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
extern "C" int getchar(); | |
// written as is to increase readability | |
bool isEnglishLetter(char c) | |
{ | |
if (c >= 'A' && c <= 'Z') | |
return true; | |
if (c >= 'a' && c <= 'z') | |
return true; | |
return false; | |
} | |
// returns true if EOF is reached, otherwise returns false | |
bool getNextWord(string &result) | |
{ | |
char c; | |
while (true) | |
{ | |
c = (char) getchar(); | |
if (c == EOF) | |
return true; | |
if (isEnglishLetter(c)) | |
result += c; | |
else | |
return false; | |
} | |
return false; | |
} | |
// get all words in the map | |
void getWordMap(vector<pair<string, int>> & result) { | |
map<string, int> dict; | |
bool eof = false; | |
while (!eof) | |
{ | |
string s; | |
eof = getNextWord(s); | |
if (s.length() == 0) | |
continue; // ignore empty words | |
if (dict.count(s) > 0) | |
dict[s]++; | |
else | |
dict[s] = 1; | |
} | |
copy(dict.begin(), dict.end(), back_inserter(result)); | |
} | |
int main() | |
{ | |
vector<pair<string, int>> plist; | |
getWordMap(plist); | |
auto cmp = [](auto &f, auto &s) { return f.second == s.second ? f.first < s.first : f.second > s.second; }; | |
std::sort(plist.begin(), plist.end(), cmp); | |
for (auto it = plist.begin(); it != plist.end(); it++) | |
cout << it->second << ' ' << it->first << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment