Advertisement
kutuzzzov

Урок 3

Sep 28th, 2022 (edited)
603
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.21 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. enum class DocumentStatus {
  62.     ACTUAL,
  63.     IRRELEVANT,
  64.     BANNED,
  65.     REMOVED
  66. };
  67.  
  68. class SearchServer {
  69. public:
  70.     // Defines an invalid document id
  71.     // You can refer to this constant as SearchServer::INVALID_DOCUMENT_ID
  72.     inline static constexpr int INVALID_DOCUMENT_ID = -1;
  73.  
  74.     SearchServer() = default;
  75.  
  76.     explicit SearchServer(const string& stop_words) {
  77.         for (const string& word : SplitIntoWords(stop_words)) {
  78.             stop_words_.insert(word);
  79.         }
  80.     }
  81.  
  82.     template <typename StringCollection>
  83.     explicit SearchServer(const StringCollection& stop_words) {
  84.         string stop_words_text;
  85.         for (const auto& text : stop_words) {
  86.             stop_words_text += " "s;
  87.             stop_words_text += text;
  88.         }
  89.         for (const auto& word : SplitIntoWords(stop_words_text)) {
  90.             stop_words_.insert(word);
  91.         }
  92.     }
  93.  
  94.     [[nodiscard]] bool AddDocument(int document_id, const string& document, DocumentStatus status, const vector<int>& ratings) {
  95.         if (document_id < 0) {
  96.             return false;
  97.         }
  98.         if (documents_.find(document_id) != documents_.end()) {
  99.             return false;
  100.         }
  101.  
  102.         const vector<string> words = SplitIntoWordsNoStop(document);
  103.         for (auto& word : words) {
  104.             if (!IsValidWord(word)) {
  105.                 return false;
  106.             }
  107.         }
  108.         for (auto& word : words) {
  109.             word_to_document_freqs_[word][document_id] += 1.0 / words.size();
  110.         }
  111.         documents_.emplace(document_id, DocumentData { ComputeAverageRating(ratings), status });
  112.         documents_index_.push_back(document_id);
  113.  
  114.         return true;
  115.     }
  116.  
  117.     int GetDocumentCount() const {
  118.         return static_cast<int>(documents_.size());
  119.     }
  120.  
  121.     template <typename DocumentPredicate>
  122.     optional<vector<Document>> FindTopDocuments(const string& raw_query, DocumentPredicate document_predicate) const {
  123.         Query query;
  124.         if (!ParseQuery(raw_query, query)) {
  125.             return nullopt;
  126.         }
  127.  
  128.         auto matched_documents = FindAllDocuments(query, document_predicate);
  129.  
  130.         sort(matched_documents.begin(), matched_documents.end(),
  131.             [](const Document& lhs, const Document& rhs) {
  132.                 const double EPSILON = 1e-6;
  133.                 if (abs(lhs.relevance - rhs.relevance) < EPSILON) {
  134.                     return lhs.rating > rhs.rating;
  135.                 }
  136.                 else {
  137.                     return lhs.relevance > rhs.relevance;
  138.                 }
  139.             });
  140.         if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
  141.             matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
  142.         }
  143.  
  144.         return matched_documents;
  145.     }
  146.  
  147.     optional<vector<Document>> FindTopDocuments(const string& raw_query, DocumentStatus status) const {
  148.         return FindTopDocuments(raw_query,
  149.             [&status](int document_id, DocumentStatus new_status, int rating) {
  150.                 return new_status == status;
  151.             });
  152.     }
  153.  
  154.     optional<vector<Document>> FindTopDocuments(const string& raw_query) const {
  155.         return FindTopDocuments(raw_query, DocumentStatus::ACTUAL);
  156.     }
  157.  
  158.     optional<tuple<vector<string>, DocumentStatus>> MatchDocument(const string& raw_query, int document_id) const {
  159.         Query query;
  160.         if (!ParseQuery(raw_query, query)) {
  161.             return nullopt;
  162.         }
  163.  
  164.         vector<string> matched_words;
  165.         for (const string& word : query.plus_words) {
  166.             if (word_to_document_freqs_.count(word) == 0) {
  167.                 continue;
  168.             }
  169.             if (word_to_document_freqs_.at(word).count(document_id)) {
  170.                 matched_words.push_back(word);
  171.             }
  172.         }
  173.         for (const string& word : query.minus_words) {
  174.             if (word_to_document_freqs_.count(word) == 0) {
  175.                 continue;
  176.             }
  177.             if (word_to_document_freqs_.at(word).count(document_id)) {
  178.                 matched_words.clear();
  179.                 break;
  180.             }
  181.         }
  182.  
  183.         return { { matched_words, documents_.at(document_id).status } };
  184.     }
  185.  
  186.     int GetDocumentId(int index) const {
  187.         if ((index >= 0) && (index < static_cast<int>(documents_.size()))) {
  188.             return documents_index_[index];
  189.         }
  190.         return SearchServer::INVALID_DOCUMENT_ID;
  191.     }
  192.  
  193. private:
  194.     struct Query {
  195.         set<string> plus_words;
  196.         set<string> minus_words;
  197.     };
  198.  
  199.     struct DocumentData {
  200.         int rating;
  201.         DocumentStatus status;
  202.     };
  203.  
  204.     map<string, map<int, double>> word_to_document_freqs_;
  205.     map<int, DocumentData> documents_;
  206.     set<string> stop_words_;
  207.     vector<int> documents_index_;
  208.  
  209.     bool IsStopWord(const string& word) const {
  210.         return stop_words_.count(word) > 0;
  211.     }
  212.  
  213.     static bool IsValidWord(const string& word) {
  214.         // A valid word must not contain special characters
  215.         return none_of(word.begin(), word.end(), [](char c) {
  216.             return c >= '\0' && c < ' ';
  217.             });
  218.     }
  219.  
  220.     vector<string> SplitIntoWordsNoStop(const string& text) const {
  221.         vector<string> words;
  222.         for (const string& word : SplitIntoWords(text)) {
  223.             if (!IsStopWord(word)) {
  224.                 words.push_back(word);
  225.             }
  226.         }
  227.         return words;
  228.     }
  229.  
  230.     static int ComputeAverageRating(const vector<int>& ratings) {
  231.         if (ratings.empty()) {
  232.             return 0;
  233.         }
  234.         int rating_sum = 0;
  235.         for (const auto rating : ratings) {
  236.             rating_sum += rating;
  237.         }
  238.         return rating_sum / static_cast<int>(ratings.size());
  239.     }
  240.  
  241.     struct QueryWord {
  242.         string data;
  243.         bool is_minus;
  244.         bool is_stop;
  245.     };
  246.  
  247.     [[nodiscard]] bool ParseQueryWord(string text, QueryWord& result) const {
  248.         result = {};
  249.  
  250.         if (text.empty()) {
  251.             return false;
  252.         }
  253.         bool is_minus = false;
  254.         if (text[0] == '-') {
  255.             is_minus = true;
  256.             text = text.substr(1);
  257.         }
  258.         if (text.empty() || text[0] == '-' || !IsValidWord(text)) {
  259.             return false;
  260.         }
  261.  
  262.         result = QueryWord{ text, is_minus, IsStopWord(text) };
  263.         return true;
  264.     }
  265.  
  266.     [[nodiscard]] bool ParseQuery(const string& text, Query& result) const {
  267.         result = {};
  268.         for (const string& word : SplitIntoWords(text)) {
  269.             QueryWord query_word;
  270.             if (!ParseQueryWord(word, query_word)) {
  271.                 return false;
  272.             }
  273.             if (!query_word.is_stop) {
  274.                 if (query_word.is_minus) {
  275.                     result.minus_words.insert(query_word.data);
  276.                 }
  277.                 else {
  278.                     result.plus_words.insert(query_word.data);
  279.                 }
  280.             }
  281.         }
  282.         return true;
  283.     }
  284.  
  285.     template<typename DocumentPredicate>
  286.     vector<Document> FindAllDocuments(const Query& query, DocumentPredicate predicate) const {
  287.         map<int, double> document_to_relevance;
  288.         for (const string& word : query.plus_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.                 const DocumentData documents_data = documents_.at(document_id);
  294.                 if (predicate(document_id, documents_data.status, documents_data.rating)) {
  295.                     const double IDF = log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
  296.                     document_to_relevance[document_id] += IDF * term_freq;
  297.                 }
  298.             }
  299.         }
  300.         for (const string& word : query.minus_words) {
  301.             if (word_to_document_freqs_.count(word) == 0) {
  302.                 continue;
  303.             }
  304.             for (const auto& [document_id, term_freq] : word_to_document_freqs_.at(word)) {
  305.                 document_to_relevance.erase(document_id);
  306.             }
  307.         }
  308.  
  309.         vector<Document> matched_documents;
  310.         for (const auto [document_id, relevance] : document_to_relevance) {
  311.             matched_documents.push_back({ document_id, relevance, documents_.at(document_id).rating });
  312.         }
  313.         return matched_documents;
  314.     }
  315. };
  316.  
  317. void PrintDocument(const Document& document) {
  318.     cout << "{ "s
  319.         << "document_id = "s << document.id << ", "s
  320.         << "relevance = "s << document.relevance << ", "s
  321.         << "rating = "s << document.rating
  322.         << " }"s << endl;
  323. }
  324.  
  325. int main() {
  326.     setlocale(LC_ALL, "Russian");
  327.  
  328.     SearchServer search_server("и в на"s);
  329.  
  330.     // Явно игнорируем результат метода AddDocument, чтобы избежать предупреждения
  331.     // о неиспользуемом результате его вызова
  332.     (void)search_server.AddDocument(1, "пушистый кот пушистый хвост"s, DocumentStatus::ACTUAL, { 7, 2, 7 });
  333.  
  334.     if (!search_server.AddDocument(1, "пушистый пёс и модный ошейник"s, DocumentStatus::ACTUAL, { 1, 2 })) {
  335.         cout << "Документ не был добавлен, так его id совпадает с уже имеющимся"s << endl;
  336.     }
  337.  
  338.     if (!search_server.AddDocument(-1, "пушистый пёс и модный ошейник"s, DocumentStatus::ACTUAL, { 1, 2 })) {
  339.         cout << "Документ не был добавлен, так его id отрицательный"s << endl;
  340.     }
  341.  
  342.     if (!search_server.AddDocument(3, "большой пёс скво\x12рец"s, DocumentStatus::ACTUAL, { 1, 3, 2 })) {
  343.         cout << "Документ не был добавлен, так как содержит спецсимволы"s << endl;
  344.     }
  345.  
  346.     if (const auto documents = search_server.FindTopDocuments("--пушистый"s)) {
  347.         for (const Document& document : *documents) {
  348.             PrintDocument(document);
  349.         }
  350.     }
  351.     else {
  352.         cout << "Ошибка в поисковом запросе"s << endl;
  353.     }
  354. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement