Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #include <fstream>
  2. #include <iterator>
  3. #include <iostream>
  4. #include <range/v3/all.hpp>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <string>
  8.  
  9. auto group() noexcept {
  10. return ranges::view::group_by([](auto&& lhs, auto&& rhs) {
  11. return std::isalpha(lhs) == std::isalpha(rhs);
  12. })
  13. | ranges::view::transform([](auto&& list) {
  14. return ranges::accumulate(list, std::string{});
  15. });
  16. }
  17.  
  18. auto remove_separators() noexcept {
  19. return ranges::view::filter([](auto&& str) {
  20. return std::all_of(str.begin(), str.end(), [](auto&& c) {
  21. return std::isalpha(c);
  22. });
  23. });
  24. }
  25.  
  26. auto restrict() noexcept {
  27. return ranges::view::filter([](auto&& str) {
  28. return str.length() >= 5 && std::all_of(str.begin(), str.end(), [](auto&& c) {
  29. return std::isalpha(c);
  30. });
  31. });
  32. }
  33.  
  34. auto lowercase() noexcept {
  35. return ranges::view::transform([](auto str) {
  36. std::transform(str.begin(), str.end(), str.begin(), [](auto&& c) {
  37. return std::tolower(c);
  38. });
  39. return str;
  40. });
  41. }
  42.  
  43. auto map() noexcept {
  44. return ranges::view::group_by([](auto&& lhs, auto&& rhs) {
  45. return lhs == rhs;
  46. })
  47. | ranges::view::transform([](auto&& list) {
  48. return std::pair(list | ranges::view::take(1), ranges::distance(list));
  49. });
  50. }
  51.  
  52. int main(int argc, char* argv[]) noexcept {
  53. if (argc != 3) {
  54. std::cout << "Usage: ./" << argv[0] << " [file] [word-amount]n";
  55. return -1;
  56. }
  57.  
  58. std::ifstream file{argv[1]};
  59. if (!file.is_open()) {
  60. std::cout << "Couldn't open file " << argv[1] << "!n";
  61. return -1;
  62. }
  63.  
  64. auto amount = 0u;
  65. try {
  66. amount = std::stoi(argv[2]);
  67. }
  68. catch (const std::exception&) {
  69. std::cout << "Invalid number " << argv[2] << "!n";
  70. }
  71.  
  72. std::vector<char> character_list;
  73. char character = '';
  74. while (file.read(&character, 1))
  75. character_list.push_back(character);
  76.  
  77. auto words = character_list | group() | remove_separators()
  78. | restrict() | lowercase() | ranges::to_<std::vector>() | ranges::action::sort;
  79.  
  80. auto highlights = words | map() | ranges::to_<std::vector>()
  81. | ranges::action::sort([](auto&& lhs, auto&& rhs) {
  82. return lhs.second > rhs.second;
  83. });
  84.  
  85. for (auto&& word : highlights | ranges::view::take(amount))
  86. std::cout << word.first << ": " << word.second << 'n';
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement