Here's a simple hash function that I use for a hash table I built. Its basically for taking a text file and stores every word in an index which represents the alphabetical order.
int generatehashkey(const char *name)
{
int x = tolower(name[0])- 97;
if (x < 0 || x > 25)
x = 26;
return x;
}
What this basically does is words are hashed according to their first letter. So, word starting with 'a' would get a hash key of 0, 'b' would get 1 and so on and 'z' would be 25. Numbers and symbols would have a hash key of 26. THere is an advantage this provides; You can calculate easily and quickly where a given word would be indexed in the hash table since its all in an alphabetical order, something like this:
Code can be found here: https://github.com/abhijitcpatil/general
Giving the following text as input: Atticus said to Jem one day, “I’d rather you shot at tin cans in the backyard, but I know you’ll go
after birds. Shoot all the blue jays you want, if you can hit ‘em, but
remember it’s a sin to kill a mockingbird.” That was the only time I
ever heard Atticus say it was a sin to do something, and I asked Miss
Maudie about it. “Your father’s right,” she said. “Mockingbirds don’t
do one thing except make music for us to enjoy. They don’t eat up
people’s gardens, don’t nest in corn cribs, they don’t do one thing
but sing their hearts out for us. That’s why it’s a sin to kill a
mockingbird.
This would be the output:
0 --> a a about asked and a Atticus a a all after at Atticus
1 --> but but blue birds. but backyard
2 --> cribs corn can cans
3 --> do don’t don’t don’t do don’t do day
4 --> eat enjoy. except ever
5 --> for for father’s
6 --> gardens go
7 --> hearts heard hit
8 --> it’s in it. I it I it’s if I in
9 --> jays Jem
10 --> kill kill know
11 -->
12 --> mockingbird. music make Maudie Miss mockingbird.”
13 --> nest
14 --> out one one only one
15 --> people’s
16 --> 17 --> right remember rather
18 --> sin sing said. she something sin say sin Shoot shot said
19 --> to That’s their thing they They to thing to time the That to the the tin to
20 --> us. up us
21 -->
22 --> why was was want
23 -->
24 --> you you you’ll you
25 -->
26 --> “Mockingbirds ” “Your ‘em “I’d
String
's ownhashCode()
? – MinefieldString.hashCode()
. Hashing to int seems a bad idea. – Weatherman