#include<bits/stdc++.h>
using namespace std;
//Chaining idea to reduce Collision
int hash_string(string name , int limit){
long long sum=0, nn =limit;
for(int i=0;i<(int)name.size();i++){
sum = (sum * 26 + name[i] - 'a') % nn;
}
return sum % nn;
}
class Entry{
public:
const static int Internal_limit=65407;
string name;//key
string phoneNumber;//data
Entry(string name,string phoneNumber):
name(name),phoneNumber(phoneNumber){
}
int hash(){
return hash_string(name,Internal_limit);
}
void print(){
cout <<setw(2)<< " ("<<name <<", "<<phoneNumber<<") "<<'\n';
}
};
class HashTable{
private:
int table_size{0};
vector<Entry*>table;
Entry* deleted = new Entry(""," ");
public:
HashTable(int table_size):table_size(table_size){
table.resize(table_size);
}
bool put(Entry phone){
int idx = phone.hash()%table_size;
//max moves is table size steps
for(int i = 0;i < (int)table_size;i++){
if(table[i]==deleted || !table[idx]){
table[idx] = new Entry (phone.name,phone.phoneNumber);
return true;
}
else if(table[idx]->name == phone.name){
//update
table[idx]->phoneNumber =phone.phoneNumber;
return true;
}
idx =(idx + 1)% table_size;
}
return false;
}
bool remove(Entry phone){
int idx = phone.hash()%table_size;
for(int i =0;i<table_size;i++){
if(!table[idx]) break;
else if(table[idx]!=deleted and table[idx]->name ==phone.name){
delete table[idx];
table[idx]=deleted;
return true;
}
//move one step
idx =(idx + 1)% table_size;
}
return false;
}
bool get(Entry phone){
int idx = phone.hash()%table_size;
for(int i =0;i<table_size;i++){
if(!table[idx]) break;
else if(table[idx]!=deleted and table[idx]->name ==phone.name){
phone.phoneNumber = table[idx]->phoneNumber;
return true;
}
//move one step
idx =(idx + 1)% table_size;
}
return false;
}
void print_all(){
for(int i = 0 ; i < table_size ; i++){
cout << i <<" ";
if(table[i]==deleted){
cout <<" X ";
}
else if(!table[i]){
cout<<" E ";
}
else{
table[i]->print();
}
cout <<'\n';
}
cout <<"*************************\n";
}
};
int main(){
HashTable table(11);
table.put(Entry("manar","13"));
table.put(Entry("manora","4"));
table.put(Entry("mona","830"));
table.put(Entry("noha","9"));
table.put(Entry("mohamed","349"));
table.put(Entry("adam","759"));
table.print_all();
cout <<"After removing noha\n";
table.remove(Entry("noha","9"));
table.print_all();
return 0;
}