shizaero

Untitled

May 8th, 2023
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.02 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <map>
  5. #include <set>
  6. #include <stdexcept>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10.  
  11. using namespace std;
  12.  
  13. const int MAX_RESULT_DOCUMENT_COUNT = 5;
  14. //Интервал, в котором находится одна страница
  15. //Содержит итератор начала, итератор конца и вспомогательные методы
  16. //Интервал, в котором находится одна страница
  17. //Содержит итератор начала, итератор конца и вспомогательные методы
  18. template <typename Iterator>
  19. class IteratorRange {
  20.     IteratorRange(Iterator it_begin, Iterator it_end) :
  21.         it_begin_(it_begin), it_end_(it_end) {}
  22.  
  23.     Iterator begin() {
  24.         return it_begin_;
  25.     }
  26.     Iterator end() {
  27.         return it_end_;
  28.     }
  29.     int size() {
  30.         return distance(it_begin_, it_end_);
  31.     }
  32. private:
  33.     Iterator it_begin_;
  34.     Iterator it_end_;
  35. };
  36.  
  37. template <typename Iterator>
  38. class Paginator {
  39. public:
  40.     Paginator(Iterator it_cont_begin, Iterator it_cont_end, size_t page_size) {
  41.         for (auto it = it_cont_begin; it < it_cont_end; ++it) {
  42.             IteratorRange page(it, advance(it, page_size));
  43.             content_.push_back(page);
  44.         }
  45.     }
  46.     auto begin() {
  47.         return content_.begin();
  48.     }
  49.     auto end() {
  50.         return content_.end();
  51.     }
  52. private:
  53.     vector<IteratorRange<Iterator>> content_;
  54. };
  55.  
  56. template <typename Container>
  57. auto Paginate(const Container& c, size_t page_size) {
  58.     return Paginator(begin(c), end(c), page_size);
  59. }
  60.  
  61. string ReadLine() {
  62.     string s;
  63.     getline(cin, s);
  64.     return s;
  65. }
  66.  
  67. int ReadLineWithNumber() {
  68.     int result;
  69.     cin >> result;
  70.     ReadLine();
  71.     return result;
  72. }
  73.  
  74. vector<string> SplitIntoWords(const string& text) {
  75.     vector<string> words;
  76.     string word;
  77.     for (const char c : text) {
  78.         if (c == ' ') {
  79.             if (!word.empty()) {
  80.                 words.push_back(word);
  81.                 word.clear();
  82.             }
  83.         }
  84.         else {
  85.             word += c;
  86.         }
  87.     }
  88.     if (!word.empty()) {
  89.         words.push_back(word);
  90.     }
  91.  
  92.     return words;
  93. }
  94.  
  95. struct Document {
  96.     Document() = default;
  97.  
  98.     Document(int id, double relevance, int rating)
  99.         : id(id)
  100.         , relevance(relevance)
  101.         , rating(rating) {
  102.     }
  103.  
  104.     int id = 0;
  105.     double relevance = 0.0;
  106.     int rating = 0;
  107. };
  108.  
  109. template <typename StringContainer>
  110. set<string> MakeUniqueNonEmptyStrings(const StringContainer& strings) {
  111.     set<string> non_empty_strings;
  112.     for (const string& str : strings) {
  113.         if (!str.empty()) {
  114.             non_empty_strings.insert(str);
  115.         }
  116.     }
  117.     return non_empty_strings;
  118. }
  119.  
  120. enum class DocumentStatus {
  121.     ACTUAL,
  122.     IRRELEVANT,
  123.     BANNED,
  124.     REMOVED,
  125. };
  126.  
  127. class SearchServer {
  128. public:
  129.     template <typename StringContainer>
  130.     explicit SearchServer(const StringContainer& stop_words)
  131.         : stop_words_(MakeUniqueNonEmptyStrings(stop_words))  // Extract non-empty stop words
  132.     {
  133.         if (!all_of(stop_words_.begin(), stop_words_.end(), IsValidWord)) {
  134.             throw invalid_argument("Some of stop words are invalid"s);
  135.         }
  136.     }
  137.  
  138.     explicit SearchServer(const string& stop_words_text)
  139.         : SearchServer(
  140.             SplitIntoWords(stop_words_text))  // Invoke delegating constructor from string container
  141.     {
  142.     }
  143.  
  144.     void AddDocument(int document_id, const string& document, DocumentStatus status,
  145.         const vector<int>& ratings) {
  146.         if ((document_id < 0) || (documents_.count(document_id) > 0)) {
  147.             throw invalid_argument("Invalid document_id"s);
  148.         }
  149.         const auto words = SplitIntoWordsNoStop(document);
  150.  
  151.         const double inv_word_count = 1.0 / words.size();
  152.         for (const string& word : words) {
  153.             word_to_document_freqs_[word][document_id] += inv_word_count;
  154.         }
  155.         documents_.emplace(document_id, DocumentData{ ComputeAverageRating(ratings), status });
  156.         document_ids_.push_back(document_id);
  157.     }
  158.  
  159.     template <typename DocumentPredicate>
  160.     vector<Document> FindTopDocuments(const string& raw_query,
  161.         DocumentPredicate document_predicate) const {
  162.         const auto query = ParseQuery(raw_query);
  163.  
  164.         auto matched_documents = FindAllDocuments(query, document_predicate);
  165.  
  166.         sort(matched_documents.begin(), matched_documents.end(),
  167.             [](const Document& lhs, const Document& rhs) {
  168.                 if (abs(lhs.relevance - rhs.relevance) < 1e-6) {
  169.                     return lhs.rating > rhs.rating;
  170.                 }
  171.                 else {
  172.                     return lhs.relevance > rhs.relevance;
  173.                 }
  174.             });
  175.         if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
  176.             matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
  177.         }
  178.  
  179.         return matched_documents;
  180.     }
  181.  
  182.     vector<Document> FindTopDocuments(const string& raw_query, DocumentStatus status) const {
  183.         return FindTopDocuments(
  184.             raw_query, [status](int document_id, DocumentStatus document_status, int rating) {
  185.                 return document_status == status;
  186.             });
  187.     }
  188.  
  189.     vector<Document> FindTopDocuments(const string& raw_query) const {
  190.         return FindTopDocuments(raw_query, DocumentStatus::ACTUAL);
  191.     }
  192.  
  193.     int GetDocumentCount() const {
  194.         return documents_.size();
  195.     }
  196.  
  197.     int GetDocumentId(int index) const {
  198.         return document_ids_.at(index);
  199.     }
  200.  
  201.     tuple<vector<string>, DocumentStatus> MatchDocument(const string& raw_query,
  202.         int document_id) const {
  203.         const auto query = ParseQuery(raw_query);
  204.  
  205.         vector<string> matched_words;
  206.         for (const string& word : query.plus_words) {
  207.             if (word_to_document_freqs_.count(word) == 0) {
  208.                 continue;
  209.             }
  210.             if (word_to_document_freqs_.at(word).count(document_id)) {
  211.                 matched_words.push_back(word);
  212.             }
  213.         }
  214.         for (const string& word : query.minus_words) {
  215.             if (word_to_document_freqs_.count(word) == 0) {
  216.                 continue;
  217.             }
  218.             if (word_to_document_freqs_.at(word).count(document_id)) {
  219.                 matched_words.clear();
  220.                 break;
  221.             }
  222.         }
  223.         return { matched_words, documents_.at(document_id).status };
  224.     }
  225.  
  226. private:
  227.     struct DocumentData {
  228.         int rating;
  229.         DocumentStatus status;
  230.     };
  231.     const set<string> stop_words_;
  232.     map<string, map<int, double>> word_to_document_freqs_;
  233.     map<int, DocumentData> documents_;
  234.     vector<int> document_ids_;
  235.  
  236.     bool IsStopWord(const string& word) const {
  237.         return stop_words_.count(word) > 0;
  238.     }
  239.  
  240.     static bool IsValidWord(const string& word) {
  241.         // A valid word must not contain special characters
  242.         return none_of(word.begin(), word.end(), [](char c) {
  243.             return c >= '\0' && c < ' ';
  244.             });
  245.     }
  246.  
  247.     vector<string> SplitIntoWordsNoStop(const string& text) const {
  248.         vector<string> words;
  249.         for (const string& word : SplitIntoWords(text)) {
  250.             if (!IsValidWord(word)) {
  251.                 throw invalid_argument("Word "s + word + " is invalid"s);
  252.             }
  253.             if (!IsStopWord(word)) {
  254.                 words.push_back(word);
  255.             }
  256.         }
  257.         return words;
  258.     }
  259.  
  260.     static int ComputeAverageRating(const vector<int>& ratings) {
  261.         if (ratings.empty()) {
  262.             return 0;
  263.         }
  264.         int rating_sum = 0;
  265.         for (const int rating : ratings) {
  266.             rating_sum += rating;
  267.         }
  268.         return rating_sum / static_cast<int>(ratings.size());
  269.     }
  270.  
  271.     struct QueryWord {
  272.         string data;
  273.         bool is_minus;
  274.         bool is_stop;
  275.     };
  276.  
  277.     QueryWord ParseQueryWord(const string& text) const {
  278.         if (text.empty()) {
  279.             throw invalid_argument("Query word is empty"s);
  280.         }
  281.         string word = text;
  282.         bool is_minus = false;
  283.         if (word[0] == '-') {
  284.             is_minus = true;
  285.             word = word.substr(1);
  286.         }
  287.         if (word.empty() || word[0] == '-' || !IsValidWord(word)) {
  288.             throw invalid_argument("Query word "s + text + " is invalid");
  289.         }
  290.  
  291.         return { word, is_minus, IsStopWord(word) };
  292.     }
  293.  
  294.     struct Query {
  295.         set<string> plus_words;
  296.         set<string> minus_words;
  297.     };
  298.  
  299.     Query ParseQuery(const string& text) const {
  300.         Query result;
  301.         for (const string& word : SplitIntoWords(text)) {
  302.             const auto query_word = ParseQueryWord(word);
  303.             if (!query_word.is_stop) {
  304.                 if (query_word.is_minus) {
  305.                     result.minus_words.insert(query_word.data);
  306.                 }
  307.                 else {
  308.                     result.plus_words.insert(query_word.data);
  309.                 }
  310.             }
  311.         }
  312.         return result;
  313.     }
  314.  
  315.     // Existence required
  316.     double ComputeWordInverseDocumentFreq(const string& word) const {
  317.         return log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
  318.     }
  319.  
  320.     template <typename DocumentPredicate>
  321.     vector<Document> FindAllDocuments(const Query& query,
  322.         DocumentPredicate document_predicate) const {
  323.         map<int, double> document_to_relevance;
  324.         for (const string& word : query.plus_words) {
  325.             if (word_to_document_freqs_.count(word) == 0) {
  326.                 continue;
  327.             }
  328.             const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
  329.             for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
  330.                 const auto& document_data = documents_.at(document_id);
  331.                 if (document_predicate(document_id, document_data.status, document_data.rating)) {
  332.                     document_to_relevance[document_id] += term_freq * inverse_document_freq;
  333.                 }
  334.             }
  335.         }
  336.  
  337.         for (const string& word : query.minus_words) {
  338.             if (word_to_document_freqs_.count(word) == 0) {
  339.                 continue;
  340.             }
  341.             for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
  342.                 document_to_relevance.erase(document_id);
  343.             }
  344.         }
  345.  
  346.         vector<Document> matched_documents;
  347.         for (const auto [document_id, relevance] : document_to_relevance) {
  348.             matched_documents.push_back(
  349.                 { document_id, relevance, documents_.at(document_id).rating });
  350.         }
  351.         return matched_documents;
  352.     }
  353. };
  354. template <typename Iterator>
  355. ostream& operator<<(ostream& output, IteratorRange<Iterator> page) {
  356.     for (const auto it = page.begin(); it < page.end(); ++it) {
  357.         output << *it << endl;
  358.     }
  359.     return output;
  360. }
  361.  
  362. int main() {
  363.     SearchServer search_server("and with"s);
  364.     search_server.AddDocument(1, "funny pet and nasty rat"s, DocumentStatus::ACTUAL, { 7, 2, 7 });
  365.     search_server.AddDocument(2, "funny pet with curly hair"s, DocumentStatus::ACTUAL, { 1, 2, 3 });
  366.     search_server.AddDocument(3, "big cat nasty hair"s, DocumentStatus::ACTUAL, { 1, 2, 8 });
  367.     search_server.AddDocument(4, "big dog cat Vladislav"s, DocumentStatus::ACTUAL, { 1, 3, 2 });
  368.     search_server.AddDocument(5, "big dog hamster Borya"s, DocumentStatus::ACTUAL, { 1, 1, 1 });
  369.     const auto search_results = search_server.FindTopDocuments("curly dog"s);
  370.     int page_size = 2;
  371.     const auto pages = Paginate(search_results, page_size);
  372.  
  373.     // Выводим найденные документы по страницам
  374.     for (auto page = pages.begin(); page != pages.end(); ++page) { // идем итератором по вектору content_ класса Paginator
  375.         cout << *page << endl; //объект IteratorRange
  376.         cout << "Page break"s << endl;
  377.     }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment