Advertisement
Petrovi4

CountWords

Aug 11th, 2022 (edited)
961
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <random>
  4. #include <string>
  5. #include <string_view>
  6. #include <execution>
  7. #include "log_duration.h"
  8.  
  9. using namespace std;
  10.  
  11. string GenerateQuery(mt19937& generator, int max_length, int space_rate) {
  12.     const int length = uniform_int_distribution(0, max_length)(generator);
  13.     string query(length, ' ');
  14.     for (char& c : query) {
  15.         const int rnd = uniform_int_distribution(0, space_rate - 1)(generator);
  16.         if (rnd > 0) {
  17.             c = 'a' + (rnd - 1);
  18.         }
  19.     }
  20.     return query;
  21. }
  22.  
  23. template <typename Solver>
  24. void Test(string_view mark, string_view s, Solver solver) {
  25.     int result;
  26.     {
  27.         LOG_DURATION(mark);
  28.         result = solver(s);
  29.     }
  30.     cout << result << endl;
  31. }
  32.  
  33. #define TEST(solver) Test(#solver, s, solver)
  34.  
  35. int CountWords(std::string_view str) {
  36.     std::size_t wc = (str.front() != ' ' ? 1 : 0);
  37.     return wc += std::transform_reduce(
  38.         execution::par,
  39.         str.begin(),
  40.         str.end()-1,
  41.         str.begin()+1,
  42.         0,
  43.         std::plus<>{}, [](char left, char right) {
  44.             return left == ' ' && right != ' ';
  45.             }
  46.         );  
  47. }
  48. int main() {
  49.     // должно вывести 3
  50.     cout << CountWords("pretty  little octopus   "sv) << endl;
  51.  
  52.     mt19937 generator;
  53.  
  54.     const string s = GenerateQuery(generator, 100'000'000, 4);
  55.  
  56.     TEST(CountWords);
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement