It might be too early on for me to ask questions in this problem set, as I am just getting started with load
. I was looking up Hash Functions, and they look a little cryptic to me. Is it possible to pass a string to a hash table that is a 3D array (int hashtable[27][27[27]
), then use a linked list for collisions on the third order (letter)? Or is a hash table actually a constant int
, and therefore cannot be a simple array of values, unless I used some sort of multiplier for the first , second, and third letter that would distinguish the order in which they were applied.
So for example, could I nest hash tables so that
int hashtable[27][27][27]
would put the word "dog"
at {4, 16, 7}
Or could I hash it to 7164
(or whatever number structure would be the most efficient)
Sorry if this makes no sense, I'm really struggling with understanding how to implement a hash function and what it can be used for.
UPDATE
I went with writing the following 'hash function' which has some of the features of a 3D array (it tracks the index # of columns plus rows, plus "depth"), but breaks the word down into smaller chunks of 3 letters, and then adds those chunks together to get the index for the word. It actually uses a 4D feature for the first letter, to separate the index roughly numbers into groups of 26 for words four letters or more.
unsigned long add_hash (void *key, int length)
{
// Copy word into pointer variable.
unsigned char *p = key;
unsigned x = 0;
unsigned long h = 0;
// For words up to four letters, mark their order and add them together.
if (length < 5)
{
for (int i = 0; i < length; i++)
{
// Account for punctuation.
if (p[i] == '\'')
{
x = pow(28, i);
h += ((27 - 'a' + 1)* x);
}
else
{
x = pow(28, i);
h += ((p[i] - 'a' + 1)* x);
}
}
}
// For longer words, recursively fold them into groups of three letter, making a new 'alphabet' with 7,000 letters.
else
{
// Move backwards from the end to help distinguish similar words of different length.
int i = length - 1;
while (i > 0)
{
for (int j = 0; j < 3; j++)
{
if (i == 0)
{
j = 3;
continue;
}
// Account for punctuation.
else if (p[i] == '\'')
{
x = pow(28, j);
h += ((27 - 'a' + 1)* x);
}
else
{
x = pow(28, j);
h += ((p[i] - 'a' + 1) * x);
}
i--;
}
}
// Possible combinations are reduced according the first letter.
h += (pow(28, 3) * (p[0] - 'a' + 1));
}
// Keep the index within the 'Hastable' range.
h = h & HASHTABLE;
// Return the word's index number.
return h;
}
It works, I'm not sure how good it is. I'm open to improving it!