-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashing.hpp
73 lines (64 loc) · 1.69 KB
/
Hashing.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#ifndef HASHING_HPP
#define HASHING_HPP
#include <stdlib.h>
#include <math.h>
class HashingMethod{
public:
virtual long int hash(const long int m, const long int k) const = 0;
long int operator()(const long int m, const long int k) const{
return this->hash(m,k);
}
virtual HashingMethod* clone() = 0;
virtual ~HashingMethod(){}
};
class DivisionMethod: public HashingMethod{
public:
inline long int hash(long int m, long int k) const{
return std::abs(k % m);
}
HashingMethod* clone(){
return new DivisionMethod();
}
};
class KnuthDivisionMethod: public HashingMethod{
public:
inline long int hash(long int m, long int k) const{
return std::abs((k*(k+3))%m);
}
HashingMethod* clone(){
return new KnuthDivisionMethod();
}
};
class MultiplicationMethod: public HashingMethod{
private:
double a;
public:
MultiplicationMethod() : a{double(rand())/RAND_MAX}{
}
inline long int hash(long int m, long int k) const{
//w = k in bits, r = m in bits
long int w = !k ? 1 : log2(std::abs(k)),
r = !m ? 1 : log2(m);
//A in [2^(w-1), 2^w]
long int A = a * (pow(2, w) - pow(2,w-1)) + pow(2,w-1);
return (A*k) % int(pow(2, w)) >> std::abs(w-r);
}
HashingMethod* clone(){
return new MultiplicationMethod();
}
};
class UniversalMethod: public HashingMethod{
private:
static const long int PRETTY_BIG_PRIME_NUMBER = 104729;
long int p, a, b;
public:
UniversalMethod(): p{PRETTY_BIG_PRIME_NUMBER}, a(double(rand())/RAND_MAX*p), b(double(rand())/RAND_MAX*p){
}
inline long int hash(long int m, long int k) const{
return std::abs(((a*k+b)%p)%m);
}
HashingMethod* clone(){
return new UniversalMethod();
}
};
#endif // HASHING_HPP