Advertisement
chevengur

СПРИНТ № 4 | Жизненный цикл объекта | Урок 6: Инициализация поисковой системы

Nov 27th, 2023 (edited)
1,414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.83 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <map>
  5. #include <set>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9.  
  10. using namespace std;
  11.  
  12. const int MAX_RESULT_DOCUMENT_COUNT = 5;
  13.  
  14. string ReadLine() {
  15.     string s;
  16.     getline(cin, s);
  17.     return s;
  18. }
  19.  
  20. int ReadLineWithNumber() {
  21.     int result;
  22.     cin >> result;
  23.     ReadLine();
  24.     return result;
  25. }
  26.  
  27. vector<string> SplitIntoWords(const string& text) {
  28.     vector<string> words;
  29.     string word;
  30.     for (const char c : text) {
  31.         if (c == ' ') {
  32.             if (!word.empty()) {
  33.                 words.push_back(word);
  34.                 word.clear();
  35.             }
  36.         }
  37.         else {
  38.             word += c;
  39.         }
  40.     }
  41.     if (!word.empty()) {
  42.         words.push_back(word);
  43.     }
  44.  
  45.     return words;
  46. }
  47.  
  48. template<typename T>
  49. set<string> SplitIntoWordsCon(const T& words){
  50.     set<string> words_space;
  51.     for(const auto& word: words){
  52.         if(!word.empty()){
  53.             words_space.insert(word);
  54.         }
  55.     }
  56.     return words_space;
  57. }
  58.  
  59. struct Document {
  60.     Document() = default;
  61.     Document(int id_, double rel_, int rating_): id(id_), relevance(rel_), rating(rating_){};
  62.     int id = 0;
  63.     double relevance = 0;
  64.     int rating = 0;
  65. };
  66.  
  67. enum class DocumentStatus {
  68.     ACTUAL,
  69.     IRRELEVANT,
  70.     BANNED,
  71.     REMOVED,
  72. };
  73.  
  74. class SearchServer {
  75. public:
  76.  
  77.     explicit SearchServer(const string& stop_words){
  78.         for (const string& word : SplitIntoWords(stop_words)) {
  79.             stop_words_.insert(word);
  80.         }
  81.     }
  82.  
  83.     template<typename Kunteynir>
  84.     explicit SearchServer(const Kunteynir& stop_words): stop_words_(SplitIntoWordsCon(stop_words)){
  85.     }
  86.  
  87.     void AddDocument(int document_id, const string& document, DocumentStatus status,
  88.         const vector<int>& ratings) {
  89.         const vector<string> words = SplitIntoWordsNoStop(document);
  90.         const double inv_word_count = 1.0 / words.size();
  91.         for (const string& word : words) {
  92.             word_to_document_freqs_[word][document_id] += inv_word_count;
  93.         }
  94.         documents_.emplace(document_id, DocumentData{ ComputeAverageRating(ratings), status });
  95.     }
  96.  
  97.     vector<Document> FindTopDocuments(const string& raw_query, DocumentStatus status) const {
  98.         return FindTopDocuments(raw_query, [status](int document_id, DocumentStatus doc_status, int rating) { return doc_status == status; });
  99.     }
  100.  
  101.  
  102.     vector<Document> FindTopDocuments(const string& raw_query) const {
  103.         return FindTopDocuments(raw_query, DocumentStatus::ACTUAL);
  104.     }
  105.  
  106.     template<typename Predicate>
  107.     vector<Document> FindTopDocuments(const string& raw_query, Predicate predicate) const {
  108.         const Query query = ParseQuery(raw_query);
  109.         auto matched_documents = FindAllDocuments(query, predicate);
  110.  
  111.         sort(matched_documents.begin(), matched_documents.end(),
  112.             [](const Document& lhs, const Document& rhs) {
  113.                 if (abs(lhs.relevance - rhs.relevance) < 1e-6) {
  114.                     return lhs.rating > rhs.rating;
  115.                 }
  116.                 else {
  117.                     return lhs.relevance > rhs.relevance;
  118.                 }
  119.             });
  120.         if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
  121.             matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
  122.         }
  123.         return matched_documents;
  124.     }
  125.  
  126.     int GetDocumentCount() const {
  127.         return documents_.size();
  128.     }
  129.  
  130.     tuple<vector<string>, DocumentStatus> MatchDocument(const string& raw_query,
  131.         int document_id) const {
  132.         const Query query = ParseQuery(raw_query);
  133.         vector<string> matched_words;
  134.         for (const string& word : query.plus_words) {
  135.             if (word_to_document_freqs_.count(word) == 0) {
  136.                 continue;
  137.             }
  138.             if (word_to_document_freqs_.at(word).count(document_id)) {
  139.                 matched_words.push_back(word);
  140.             }
  141.         }
  142.         for (const string& word : query.minus_words) {
  143.             if (word_to_document_freqs_.count(word) == 0) {
  144.                 continue;
  145.             }
  146.             if (word_to_document_freqs_.at(word).count(document_id)) {
  147.                 matched_words.clear();
  148.                 break;
  149.             }
  150.         }
  151.         return { matched_words, documents_.at(document_id).status };
  152.     }
  153.  
  154. private:
  155.     struct DocumentData {
  156.         int rating;
  157.         DocumentStatus status;
  158.     };
  159.  
  160.     set<string> stop_words_;
  161.     map<string, map<int, double>> word_to_document_freqs_;
  162.     map<int, DocumentData> documents_;
  163.  
  164.     bool IsStopWord(const string& word) const {
  165.         return stop_words_.count(word) > 0;
  166.     }
  167.  
  168.     vector<string> SplitIntoWordsNoStop(const string& text) const {
  169.         vector<string> words;
  170.         for (const string& word : SplitIntoWords(text)) {
  171.             if (!IsStopWord(word)) {
  172.                 words.push_back(word);
  173.             }
  174.         }
  175.         return words;
  176.     }
  177.  
  178.     static int ComputeAverageRating(const vector<int>& ratings) {
  179.         if (ratings.empty()) {
  180.             return 0;
  181.         }
  182.         int rating_sum = 0;
  183.         for (const int rating : ratings) {
  184.             rating_sum += rating;
  185.         }
  186.         return rating_sum / static_cast<int>(ratings.size());
  187.     }
  188.  
  189.     struct QueryWord {
  190.         string data;
  191.         bool is_minus;
  192.         bool is_stop;
  193.     };
  194.  
  195.     QueryWord ParseQueryWord(string text) const {
  196.         bool is_minus = false;
  197.         // Word shouldn't be empty
  198.         if (text[0] == '-') {
  199.             is_minus = true;
  200.             text = text.substr(1);
  201.         }
  202.         return { text, is_minus, IsStopWord(text) };
  203.     }
  204.  
  205.     struct Query {
  206.         set<string> plus_words;
  207.         set<string> minus_words;
  208.     };
  209.  
  210.     Query ParseQuery(const string& text) const {
  211.         Query query;
  212.         for (const string& word : SplitIntoWords(text)) {
  213.             const QueryWord query_word = ParseQueryWord(word);
  214.             if (!query_word.is_stop) {
  215.                 if (query_word.is_minus) {
  216.                     query.minus_words.insert(query_word.data);
  217.                 }
  218.                 else {
  219.                     query.plus_words.insert(query_word.data);
  220.                 }
  221.             }
  222.         }
  223.         return query;
  224.     }
  225.  
  226.     // Existence required
  227.     double ComputeWordInverseDocumentFreq(const string& word) const {
  228.         return log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
  229.     }
  230.  
  231.     template<typename Docpredicate>
  232.     vector<Document> FindAllDocuments(const Query& query, Docpredicate predicate) const {
  233.         map<int, double> document_to_relevance;
  234.         for (const string& word : query.plus_words) {
  235.             if (word_to_document_freqs_.count(word) == 0) {
  236.                 continue;
  237.             }
  238.             const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
  239.             for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
  240.                 if (predicate(document_id, documents_.at(document_id).status, documents_.at(document_id).rating)) {
  241.                     document_to_relevance[document_id] += term_freq * inverse_document_freq;
  242.                 }
  243.             }
  244.         }
  245.  
  246.         for (const string& word : query.minus_words) {
  247.             if (word_to_document_freqs_.count(word) == 0) {
  248.                 continue;
  249.             }
  250.             for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
  251.                 document_to_relevance.erase(document_id);
  252.             }
  253.         }
  254.  
  255.         vector<Document> matched_documents;
  256.         for (const auto [document_id, relevance] : document_to_relevance) {
  257.             matched_documents.push_back(
  258.                 { document_id, relevance, documents_.at(document_id).rating });
  259.         }
  260.         return matched_documents;
  261.     }
  262. };
  263.  
  264. void PrintDocument(const Document& document) {
  265.     cout << "{ "s
  266.         << "document_id = "s << document.id << ", "s
  267.         << "relevance = "s << document.relevance << ", "s
  268.         << "rating = "s << document.rating
  269.         << " }"s << endl;
  270. }
  271. int main() {
  272.     const vector<string> stop_words_vector = {"и"s, "в"s, "на"s, ""s, "в"s};
  273.     const string a = "b"s;
  274.     SearchServer search_server(a);
  275.     SearchServer search_server1(stop_words_vector);
  276.     search_server.AddDocument(0, "белый кот и модный ошейник"s, DocumentStatus::ACTUAL, { 8, -3 });
  277.     search_server.AddDocument(1, "пушистый кот пушистый хвост"s, DocumentStatus::ACTUAL, { 7, 2, 7 });
  278.     search_server.AddDocument(2, "ухоженный пёс выразительные глаза"s, DocumentStatus::ACTUAL, { 5, -12, 2, 1 });
  279.     search_server.AddDocument(3, "ухоженный скворец евгений"s, DocumentStatus::BANNED, { 9 });
  280.     cout << "ACTUAL by default:"s << endl;
  281.     for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s)) {
  282.         PrintDocument(document);
  283.     }
  284.     cout << "ACTUAL:"s << endl;
  285.     for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s, [](int document_id, DocumentStatus status, int rating) { return status == DocumentStatus::ACTUAL; })) {
  286.         PrintDocument(document);
  287.     }
  288.     cout << "Even ids:"s << endl;
  289.     for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s, [](int document_id, DocumentStatus status, int rating) { return document_id % 2 == 0; })) {
  290.         PrintDocument(document);
  291.     }
  292.     return 0;
  293. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement