giGii

good_or_bad_hash

May 15th, 2023 (edited)
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <unordered_map>
  2. #include <string>
  3. #include <cassert>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <iostream>
  7.  
  8. using namespace std;
  9.  
  10. struct GoodHasher {
  11.     size_t operator() (std::pair<size_t, size_t> from_to) const {
  12.         return from_to.first * 37 + from_to.second * 37 * 37 + (from_to.first + from_to.second) * 37 * 37 * 37;
  13.     }
  14. };
  15. struct BadHasher {
  16.     size_t operator() (std::pair<size_t, size_t> from_to) const {
  17.         return from_to.first * 37 + from_to.second * 37 * 37;
  18.     }
  19. };
  20.  
  21. int main() {
  22.     GoodHasher good;
  23.     BadHasher bad;
  24.  
  25.     vector<pair<size_t, size_t>> vec_pair_sizet;
  26.  
  27.     size_t n, limit;
  28.     cin >> n >> limit;
  29.  
  30.     for (size_t i = 0; i < n; ++i) {
  31.         for (size_t j = i + 1; j <= n; ++j) {
  32.             vec_pair_sizet.push_back({i, j});
  33.             vec_pair_sizet.push_back({j, i});
  34.         }
  35.     }
  36.  
  37.     cout << vec_pair_sizet.size() << endl;
  38.  
  39.     sort(vec_pair_sizet.begin(), vec_pair_sizet.end());
  40.  
  41.     cout << limit << endl;
  42.  
  43.     unordered_map<size_t, size_t> for_good_hasher;
  44.     unordered_map<size_t, size_t> for_bad_hasher;
  45.  
  46.     for (const auto& p : vec_pair_sizet) {
  47.         auto ghash = good(p);
  48.         if (for_good_hasher.count(ghash) == 0) {
  49.             for_good_hasher[ghash] = 0;
  50.         }
  51.         ++for_good_hasher.at(ghash);
  52.  
  53.         auto bhash = bad(p);
  54.         if (for_bad_hasher.count(bhash) == 0) {
  55.             for_bad_hasher[bhash] = 0;
  56.         }
  57.         ++for_bad_hasher.at(bhash);
  58.     }
  59.  
  60.     size_t good_hashes = 0;
  61.  
  62.     for (const auto& [k, v] : for_good_hasher) {
  63.         if (v >= limit) {
  64.             ++good_hashes;
  65.         }
  66.     }
  67.  
  68.     size_t bad_hashes = 0;
  69.     for (const auto& [k, v] : for_bad_hasher) {
  70.         if (v >= limit) {
  71.             ++bad_hashes;
  72.         }
  73.     }
  74.  
  75.     cout << "for good hasher buckets with "s << limit << " and more collisions = "s << good_hashes << endl;
  76.     cout << "for bad hasher buckets with "s << limit << " and more collisions = "s << bad_hashes << endl;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment