-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathword-count-engine.cpp
80 lines (69 loc) · 1.89 KB
/
word-count-engine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <string>
#include <vector>
#include <ctype.h>
#include <unordered_map>
#include <map>
using namespace std;
vector<string> allWords(const string& document ) {
vector<string> words;
string word;
for (char c : document) {
if (ispunct(c)) continue;
if (isalpha(c)) {
word += tolower(c);
} else if (c == ' ' && word != "") {
words.push_back(word);
word = "";
}
}
if (word != "") words.push_back(word);
return words;
}
vector<vector<string>> wordCountEngine( const string& document )
{
// your code goes here
vector<string> words = allWords(document);
unordered_map<string, pair<int, int>> m;
int i = 0;
for (string w : words) {
auto it = m.find(w);
if (it != m.end()) {
(it->second).first++;
} else {
m[w] = pair<int, int> (1, i);
}
i++;
}
multimap<pair<int, int>, string, function<bool (pair<int, int>, pair<int, int>)>>
m2([](const pair<int, int> a, const pair<int, int> b) {
if (a.first == b.first) {
return a.second < b.second;
}
return a.first > b.first;
});
for (auto it = m.begin(); it != m.end(); it++) {
pair<int, int> f((it->second).first, (it->second).second);
string w = it->first;
m2.insert({f, w});
}
vector<vector<string>> result;
for (auto it = m2.begin(); it != m2.end(); it++) {
vector<string> wordAndCount;
wordAndCount.push_back(it->second);
wordAndCount.push_back(to_string((it->first).first));
result.push_back(wordAndCount);
}
return result;
}
int main() {
string data = "Practice makes perfect. you'll only get Perfect by practice. just practice!";
vector<vector<string>> words = wordCountEngine(data);
for (vector<string> w : words) {
for (string s : w) {
cout << s;
}
cout << endl;
}
return 0;
}