You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.4 KiB
67 lines
1.4 KiB
6 months ago
|
/**
|
||
|
* File: simple_hash.cpp
|
||
|
* Created Time: 2023-06-21
|
||
|
* Author: krahets (krahets@163.com)
|
||
|
*/
|
||
|
|
||
|
#include "../utils/common.hpp"
|
||
|
|
||
|
/* Additive hash */
|
||
|
int addHash(string key) {
|
||
|
long long hash = 0;
|
||
|
const int MODULUS = 1000000007;
|
||
|
for (unsigned char c : key) {
|
||
|
hash = (hash + (int)c) % MODULUS;
|
||
|
}
|
||
|
return (int)hash;
|
||
|
}
|
||
|
|
||
|
/* Multiplicative hash */
|
||
|
int mulHash(string key) {
|
||
|
long long hash = 0;
|
||
|
const int MODULUS = 1000000007;
|
||
|
for (unsigned char c : key) {
|
||
|
hash = (31 * hash + (int)c) % MODULUS;
|
||
|
}
|
||
|
return (int)hash;
|
||
|
}
|
||
|
|
||
|
/* XOR hash */
|
||
|
int xorHash(string key) {
|
||
|
int hash = 0;
|
||
|
const int MODULUS = 1000000007;
|
||
|
for (unsigned char c : key) {
|
||
|
hash ^= (int)c;
|
||
|
}
|
||
|
return hash & MODULUS;
|
||
|
}
|
||
|
|
||
|
/* Rotational hash */
|
||
|
int rotHash(string key) {
|
||
|
long long hash = 0;
|
||
|
const int MODULUS = 1000000007;
|
||
|
for (unsigned char c : key) {
|
||
|
hash = ((hash << 4) ^ (hash >> 28) ^ (int)c) % MODULUS;
|
||
|
}
|
||
|
return (int)hash;
|
||
|
}
|
||
|
|
||
|
/* Driver Code */
|
||
|
int main() {
|
||
|
string key = "Hello algorithm";
|
||
|
|
||
|
int hash = addHash(key);
|
||
|
cout << "Additive hash value is " << hash << endl;
|
||
|
|
||
|
hash = mulHash(key);
|
||
|
cout << "Multiplicative hash value is " << hash << endl;
|
||
|
|
||
|
hash = xorHash(key);
|
||
|
cout << "XOR hash value is " << hash << endl;
|
||
|
|
||
|
hash = rotHash(key);
|
||
|
cout << "Rotational hash value is " << hash << endl;
|
||
|
|
||
|
return 0;
|
||
|
}
|