Advertisement
Guest User

Hash test

a guest
May 20th, 2016
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3.  
  4. using namespace std;
  5.  
  6. uint64_t hashf1(const char *str) // XOR version
  7. {
  8.     uint64_t hash = 5381;
  9.     int c;
  10.  
  11.     while (c = *str++)
  12.     hash = ((hash << 5) + hash) ^ c; /* hash * 33 ^ c */
  13.  
  14.     return hash;
  15. }
  16. uint64_t hashf2(const char *str) // + version
  17. {
  18.     uint64_t hash = 5381;
  19.     int c;
  20.  
  21.     while (c = *str++)
  22.     hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
  23.  
  24.     return hash;
  25. }
  26.  
  27.  
  28. void EvaluateHash(uint64_t (*bad_hash)(const char *)){
  29.     std::map<uint64_t, std::string> hashes;
  30.     const char *charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  31.     for(const char *i=charset; *i!=0; ++i){
  32.         for(const char *j=charset; *j!=0; ++j){
  33.             char str[3]={*i,*j,0};
  34.  
  35.             uint64_t hash=bad_hash(str);
  36.             if(hashes.count(hash)){
  37.                 std::cout<<str<<","<<hashes[hash]<<" to "<<hash<<std::endl;
  38.             }else{
  39.                 hashes[hash]=std::string(str);
  40.             }
  41.         }
  42.     }
  43.     std::cout<<"*************************************************************************************************************"<<std::endl;
  44. }
  45.  
  46. int main()
  47. {
  48.     //cout << "Hello world!" << bad_hash("g5")<<","<<bad_hash("as")<<endl;
  49.     std::cout<<"hashf1:"<<std::endl;
  50.     EvaluateHash(hashf1);
  51.     std::cout<<"hashf2:"<<std::endl;
  52.     EvaluateHash(hashf2);
  53.  
  54.     std::cout<<"demo for how longer strings collide"<<std::endl;
  55.  
  56.  
  57.     // observe what happens when your hash function is linear: you can get a collision in a longer string
  58.     std::cout<<hashf2("Some longer string bA bla bla")<<std::endl;
  59.     std::cout<<hashf2("Some longer string ab bla bla")<<std::endl;
  60.  
  61.     std::cout<<hashf1("Some longer string cb bla bla")<<std::endl;
  62.     std::cout<<hashf1("Some longer string bC bla bla")<<std::endl;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement