-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knuth_Multiplicative_Quadratic_Hashing.cpp
85 lines (76 loc) · 1.32 KB
/
Knuth_Multiplicative_Quadratic_Hashing.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned ll
ull m;
struct pr
{
string word;
ull _hash;
};
pr *hashmap;
ull hx(string str)
{
ull i = 0, Id = 0;
while(str[i])
{
Id += str[i] - 'a';
Id <<= 2;
i++;
}
return Id;
}
ull knuth_multiplicative_hash(ull key)
{
ull knuth = 2654435769;
return (key * knuth) % m;
}
ull quadratic_hash(ull k, ull i)
{
return (knuth_multiplicative_hash(k) + i * i + i) % m;
}
bool insert(ull key, string value)
{
ull i = 0;
ull index = quadratic_hash(key, i);
if(hashmap[index]._hash == key)
return true;
while(hashmap[index].word != "")
{
i++;
index = quadratic_hash(key, i);
if(hashmap[index]._hash == key)
return true;
}
hashmap[index].word = value;
hashmap[index]._hash = key;
return false;
}
void tokenize(string str)
{
istringstream ss(str);
do {
string word;
ss >> word;
insert(hx(word), word);
} while(ss);
}
int main()
{
string str;
cout << "Enter table size : ";
cin >> m;
getchar();
hashmap = new pr[m];
cout << "Enter elements in one line: ";
getline(cin, str);
transform(str.begin(), str.end(), str.begin(), ::tolower);
tokenize(str);
cout << "The Hash Table:" << endl;
for(ull i = 0 ; i < m; i++)
{
if(hashmap[i].word != "")
cout << "hashmap[" << i << "] = " << hashmap[i].word << endl;
}
return 0;
}