-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathc# program to create a hash function.cs
58 lines (42 loc) · 1.15 KB
/
c# program to create a hash function.cs
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
// C# Program to create a Hash
// Function for String data
using System;
class Geeks {
// Main Method
public static void Main(String []args)
{
// Declaring the an string array
string[] values = new string[50];
string str;
// Values of the keys stored
string[] keys = new string[] {"C", "C++",
"Java", "Python", "C#", "HTML"};
int hashCode;
for (int k = 0; k < 5; k++) {
str = keys[k];
hashCode = HashFunction2(str, values);
// Storing keys at their hashcode's index
values[hashCode] = str;
}
// Displaying Hashcodes along with key values
for (int k = 0; k < (values.GetUpperBound(0)); k++) {
if (values[k] != null)
Console.WriteLine(k + " " + values[k]);
}
}
// Defining the hash function
static int HashFunction2(string s, string[] array)
{
long total = 0;
char[] c;
c = s.ToCharArray();
// Horner's rule for generating a polynomial
// of 11 using ASCII values of the characters
for (int k = 0; k <= c.GetUpperBound(0); k++)
total += 11 * total + (int)c[k];
total = total % array.GetUpperBound(0);
if (total < 0)
total += array.GetUpperBound(0);
return (int)total;
}
}