pikabuka

Theme 8 _ Lesson 6

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