forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmap.cpp
More file actions
158 lines (126 loc) · 2.19 KB
/
Hashmap.cpp
File metadata and controls
158 lines (126 loc) · 2.19 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <iostream>
using namespace std;
class node{
public:
int value;
string key;
node* next;
node(string key,int value){
this->key=key;
this->value=value;
next=NULL;
}
};
// template<typename T>
class Hashmap{
int hashFn(string key){
int ans=0;
int mul=1;
for(int i=0;key[i]!='\0';i++){
ans += key[i]*mul;
mul *= 37;
ans %= ms;
mul %= ms;
}
ans %= ms;
return ans;
}
void rehash(){
node** oldBucket=Bucket;
int oldts=ms;
cs=0;
ms=2*ms;
Bucket=new node*[ms];
for(int i=0;i<ms;i++){
Bucket[i]=NULL;
}
for(int i=0;i<oldts;i++){
node* temp=oldBucket[i];
while(temp){
insert(temp->key,temp->value);
temp=temp->next;
}
if(oldBucket[i]!=NULL){
delete oldBucket[i];
}
}
delete []oldBucket;
}
public:
node** Bucket;
int cs;
int ms; // ms:table size
Hashmap(int s=7){
cs=0;
ms=s;
Bucket=new node*[ms];
// Initialize all Buckets with Null as pointers should be NULL when they don't
// point any valid address
for(int i=0;i<s;i++){
Bucket[i]=NULL;
}
}
void insert(string key,int value){
int i=hashFn(key);cb
node* n=new node(key,value);
n->next=Bucket[i];
Bucket[i]=n;
cs++;
float load_factor=cs/(ms*1.0);
if(load_factor>0.7){
rehash();
}
}
node* Search(string key){
int i=hashFn(key);
node* temp=Bucket[i];
while(temp){
if(temp->key==key){
return temp;
}
temp=temp->next;
}
return NULL;
}
int& operator[](string key){
node* temp=Search(key);
if(temp==NULL){
// key does not exists that means create key and insert its value
int garbage;
insert(key,garbage);
temp=Search(key);
return temp->value;
}
else{
// Key exists so update its value
return temp->value;
}
}
void print(){
for(int i=0;i<ms;i++){
cout<<i<<"-->";
node* temp=Bucket[i];
while(temp){
cout<<temp->key<<",";
temp=temp->next;
}
cout<<endl;
}
}
void Delete(string key){
int i=hashFn(key);
// Homework
}
};
int main(){
Hashmap h;
h.insert("Mango",100);
h.insert("Pineapple",30);
h["Apple"]=140; // Insertion
h["Apple"]=200; // Updation
cout<<h["Apple"]<<endl; // search
h["Kiwi"]=80;
h["Banana"]=60;
h.print();
return 0;
}