using
System;
using
System.Text;
public
class
Node<T>
{
public
string
Key {
get
;
set
; }
public
T Value {
get
;
set
; }
public
Node<T> Next {
get
;
set
; }
public
Node(
string
key, T value)
{
Key = key;
Value = value;
Next =
null
;
}
}
public
class
HashMap<T>
{
private
int
numOfElements;
private
int
capacity;
private
Node<T>[] arr;
public
HashMap()
{
capacity = 1;
numOfElements = 0;
arr =
new
Node<T>[capacity];
arr[0] =
null
;
}
private
int
HashFunction(
string
key)
{
long
sum = 0;
long
factor = 31;
foreach
(
char
c
in
key)
{
sum = (sum % capacity + (
int
)c * factor % capacity) % capacity;
factor = (factor % (
int
)
ushort
.MaxValue * 31 % (
int
)
ushort
.MaxValue) %
(
int
)
ushort
.MaxValue;
}
return
(
int
)sum;
}
private
float
GetLoadFactor()
{
return
(
float
)(numOfElements + 1) / capacity;
}
private
void
Rehashing()
{
int
oldCapacity = capacity;
Node<T>[] temp = arr;
capacity = oldCapacity * 2;
arr =
new
Node<T>[capacity];
for
(
int
i = 0; i < capacity; i++)
{
arr[i] =
null
;
}
for
(
int
i = 0; i < oldCapacity; i++)
{
Node<T> currBucketHead = temp[i];
while
(currBucketHead !=
null
)
{
Insert(currBucketHead.Key, currBucketHead.Value);
currBucketHead = currBucketHead.Next;
}
}
Array.Clear(temp, 0, temp.Length);
}
public
void
Insert(
string
key, T value)
{
while
(GetLoadFactor() > 0.5f)
{
Rehashing();
}
int
bucketIndex = HashFunction(key);
if
(arr[bucketIndex] ==
null
)
{
Node<T> newNode =
new
Node<T>(key, value);
arr[bucketIndex] = newNode;
}
else
{
Node<T> newNode =
new
Node<T>(key, value);
newNode.Next = arr[bucketIndex];
arr[bucketIndex] = newNode;
}
}
public
T Search(
string
key)
{
int
bucketIndex = HashFunction(key);
Node<T> bucketHead = arr[bucketIndex];
while
(bucketHead !=
null
)
{
if
(bucketHead.Key == key)
{
return
bucketHead.Value;
}
bucketHead = bucketHead.Next;
}
Console.WriteLine(
"Oops!! Data not found."
);
return
default
(T);
}
}
class
Program
{
static
void
Main()
{
HashMap<
int
> hashMap =
new
HashMap<
int
>();
hashMap.Insert(
"Manish"
, 16);
hashMap.Insert(
"Vartika"
, 14);
hashMap.Insert(
"ITT"
, 5);
hashMap.Insert(
"elite_Programmer"
, 4);
hashMap.Insert(
"pluto14"
, 14);
hashMap.Insert(
"GeeksForGeeks"
, 11);
Console.WriteLine(
"Value of GeeksForGeeks: "
+ hashMap.Search(
"GeeksForGeeks"
));
Console.WriteLine(
"Value of ITT: "
+ hashMap.Search(
"ITT"
));
Console.WriteLine(
"Value of Manish: "
+ hashMap.Search(
"Manish"
));
Console.WriteLine(
"Value of Vartika: "
+ hashMap.Search(
"Vartika"
));
Console.WriteLine(
"Value of elite_Programmer: "
+ hashMap.Search(
"elite_Programmer"
));
Console.WriteLine(
"Value of pluto14: "
+ hashMap.Search(
"pluto14"
));
hashMap.Search(
"GFG"
);
}
}