Advertisement
kutuzzzov

Урок 6

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