Guest User

Untitled

a guest
Feb 20th, 2020
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <istream>
  3. #include <random>
  4. #include <string>
  5. #include <utility>
  6. #include <map>
  7. #include <sstream>
  8.  
  9. std::string random_line(std::istream& input)
  10. {
  11.     static auto gen = std::mt19937{std::random_device{}()};
  12.     auto count = 0u;
  13.     auto selected = std::string{};
  14.     std::string line;
  15.     while (std::getline(input, line)) {
  16.         if (std::uniform_int_distribution{0u,count++}(gen) == 0) {
  17.             selected = std::move(line);
  18.         }
  19.     }
  20.     return selected;
  21. }
  22.  
  23. int main()
  24. {
  25.     auto const lines = "one\n"
  26.                        "two\n"
  27.                        "three\n"
  28.                        "four\n"
  29.                        "five\n"
  30.                        "six\n";
  31.     auto counts = std::map<std::string,unsigned int>{};
  32.     for (auto i = 0;  i < 120000;  ++i) {
  33.         auto is = std::istringstream{lines};
  34.         ++counts[random_line(is)];
  35.     }
  36.  
  37.     {
  38.         // print the counts
  39.         auto is = std::istringstream{lines};
  40.         std::string line;
  41.         while (std::getline(is, line)) {
  42.             std::cout << line << ": " << counts[line] << '\n';
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment