Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- using namespace std;
- uint64_t hashf1(const char *str) // XOR version
- {
- uint64_t hash = 5381;
- int c;
- while (c = *str++)
- hash = ((hash << 5) + hash) ^ c; /* hash * 33 ^ c */
- return hash;
- }
- uint64_t hashf2(const char *str) // + version
- {
- uint64_t hash = 5381;
- int c;
- while (c = *str++)
- hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
- return hash;
- }
- void EvaluateHash(uint64_t (*bad_hash)(const char *)){
- std::map<uint64_t, std::string> hashes;
- const char *charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- for(const char *i=charset; *i!=0; ++i){
- for(const char *j=charset; *j!=0; ++j){
- char str[3]={*i,*j,0};
- uint64_t hash=bad_hash(str);
- if(hashes.count(hash)){
- std::cout<<str<<","<<hashes[hash]<<" to "<<hash<<std::endl;
- }else{
- hashes[hash]=std::string(str);
- }
- }
- }
- std::cout<<"*************************************************************************************************************"<<std::endl;
- }
- int main()
- {
- //cout << "Hello world!" << bad_hash("g5")<<","<<bad_hash("as")<<endl;
- std::cout<<"hashf1:"<<std::endl;
- EvaluateHash(hashf1);
- std::cout<<"hashf2:"<<std::endl;
- EvaluateHash(hashf2);
- std::cout<<"demo for how longer strings collide"<<std::endl;
- // observe what happens when your hash function is linear: you can get a collision in a longer string
- std::cout<<hashf2("Some longer string bA bla bla")<<std::endl;
- std::cout<<hashf2("Some longer string ab bla bla")<<std::endl;
- std::cout<<hashf1("Some longer string cb bla bla")<<std::endl;
- std::cout<<hashf1("Some longer string bC bla bla")<<std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement