Hi Friends, I am new to C Programming. I am working with Hash Functions. I am trying for using a simple hash function: that adda up the ascii value of each character in 'name' and returns `sum'o modulo HASH_TABLE_SIZE int symtbl_hash(char *name) { } Can anyone halp me in creating this functions. Any sort of help appreciated. Thanks in advance.
nepal_123 · Feb 5, 2011 3:42 PM · 13,696 views
I think you need to clarrify a bit. You are writing a hashfunction but you want the size of the hastable? Well i dont think, first of all, you should have same funtion for both hash function and hastable. Getting character ascii value should be easy and one googling away. So, I am trying to understand if there is more than what I understood.
Maverick · Feb 5, 2011 4:21 PM
Hi Maverick, In order to hash for a string, I would like to add the ASCII values of all the characters in that string and call it a SUM. Then I would like to have SUM % Table_Size. Let Table size be 1024 for example. The Function prototype is : int hash(char *name) { } where *name is the pointer to the address of string.
nepal_123 · Feb 5, 2011 4:44 PM
how abt something like below, havent compiled, dont have a compiler :) This should return the sum of the ascii values. int hash(char *name) { int sum = 0; int i; for (i = 0; i < strlen(name); i++) { sum = sum + name[i]; } return sum; }
prankster · Feb 5, 2011 8:17 PM
found an online compiler, dont know how long this link is valid http://codepad.org/xNaHQtR5 This is what it returned me ascii for A = 65 Link: http://codepad.org/xNaHQtR5&nb... code | output | fork ] Save this paste Delete this paste C, pasted 2 minutes ago: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 int hash(char *name) { int sum = 0; int i; for (i=0; i < strlen(name); i++) { sum = sum + name[i]; } return sum; } int main() { int test = hash("AA"); printf("%d", test); return 0; } Output: 1 130 happy coding..
prankster · Feb 5, 2011 8:19 PM
I think he is trying to create a most simple version of a Hash Table, where sum of ascii values of a string is the hash code. And to get the index in the hash table, he needs to mod the sum by the table size: prankster bro ko solution should be: return sum%HASH_TABLE_SIZE; // Given that HASH_TABLE_SIZE is a const defined somewhere in the code
nepalithitho · Feb 5, 2011 8:26 PM
thats right nepalithito, just wanted to let him know how he can get the sum, the mod should be simple like you've given
prankster · Feb 5, 2011 8:30 PM
This conversation is preserved exactly as it was on the original Sajha.com and can't accept new replies.
Start a New Discussion