-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzipfslaw.cc
100 lines (77 loc) · 2.05 KB
/
zipfslaw.cc
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// William Sjöblom
#include <iostream>
#include <unordered_map>
#include <cctype>
#include <algorithm>
#include <string>
#include <vector>
inline void downcase(std::string& s) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}
void eat_crap(std::string::iterator& begin, std::string::iterator end) {
while (begin != end && !isalpha(*begin))
begin++;
}
void eat_token(std::string::iterator& begin, std::string::iterator end) {
while (begin != end && isalpha(*begin))
begin++;
}
/**
* Strip punctuation.
*/
bool tokenize(std::string& s, std::vector<std::string>& tokens) {
std::string::iterator it = s.begin();
std::string::iterator start;
while (it != s.end()) {
eat_crap(it, s.end());
if (it != s.end()) {
start = it;
eat_token(it, s.end());
std::string token(start, it);
downcase(token);
//std::cout << token << std::endl;
if (token == "endoftext") {
return false;
}
tokens.push_back(token);
}
}
return true;
}
void solve(int n) {
//std::cout << n << std::endl;
std::unordered_map<std::string, int> histogram;
std::vector<std::string> tokens;
std::string line;
while (std::getline(std::cin, line)) {
if (!tokenize(line, tokens)) break;
}
for (std::string& token : tokens) {
histogram[token]++;
}
histogram["endoftext"] = -1;
// for (auto token : tokens) {
// std::cout << token << std::endl;
// }
std::vector<std::string> results;
int words = 0;
for (auto& [s, occ] : histogram) {
if (occ == n) {
results.push_back(s);
words++;
}
}
if (!words) {
std::cout << "There is no such word." << std::endl;
}
std::sort(results.begin(), results.end());
for (auto& result : results) {
std::cout << result << std::endl;
}
}
int main() {
int n;
while (std::cin >> n) {
solve(n);
}
}