Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "test_runner.h"
- #include "profile.h"
- #include <map>
- #include <string>
- #include <future>
- #include <functional>
- #include <algorithm>
- #include <exception>
- using namespace std;
- struct Stats {
- map<string, int> word_frequences;
- void operator += (const Stats& other){
- for(auto &it : other.word_frequences){
- if(word_frequences.find(it.first)==word_frequences.end())
- {
- word_frequences[it.first]=0;
- }
- word_frequences[it.first] +=it.second;
- }
- }
- };
- Stats ExploreLine(const set<string>& key_words, const string& line) {
- Stats res;
- istringstream str(line);
- string space;
- while(!str.eof()){
- str >> space;
- if(key_words.find(space)!=key_words.end()){
- res.word_frequences[space]++;
- }
- }
- return res;
- }
- Stats ThreadExplore(const set<string>& key_words,istream &input){
- Stats res;
- string line;
- while(!input.eof()){
- getline(input,line);
- res+= ExploreLine(key_words,line);
- }
- return res;
- }
- Stats ExploreKeyWordsSingleThread(
- const set<string>& key_words, istream& input
- ) {
- Stats result;
- for (string line; getline(input, line); ) {
- result += ExploreLine(key_words, line);
- }
- return result;
- }
- Stats ExploreKeyWords(const set<string>& key_words, istream& input) {
- Stats result;
- unsigned concurentThreadsSupported = thread::hardware_concurrency();
- vector<future<Stats>> space(concurentThreadsSupported);
- for(int i = 0;i<concurentThreadsSupported;i++){
- space[i]=async([&key_words,&input](){
- return ThreadExplore(key_words,input);
- });
- }
- for(auto &it:space){
- result+=it.get();
- }
- return result;
- }
- void TestBasic() {
- const set<string> key_words = {"yangle", "rocks", "sucks", "all"};
- stringstream ss;
- ss << "this new yangle service really rocks\n";
- ss << "It sucks when yangle isn't available\n";
- ss << "10 reasons why yangle is the best IT company\n";
- ss << "yangle rocks others suck\n";
- ss << "Goondex really sucks, but yangle rocks. Use yangle\n";
- const auto stats = ExploreKeyWords(key_words, ss);
- const map<string, int> expected = {
- {"yangle", 6},
- {"rocks", 2},
- {"sucks", 1}
- };
- ASSERT_EQUAL(stats.word_frequences, expected);
- }
- int main() {
- TestRunner tr;
- RUN_TEST(tr, TestBasic);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement