Thread: Hashing In C
View Single Post
Old Jan 8th, 2008, 8:28 PM   #3
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,886
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: Hashing In C

It's for a contest, so written code can be brought with us, but only if it's our own. And if it's too long, I can't spend 20+ minutes typing it all out from my notes, so it has to be something compact.

This is the current solution I have. I tried to keep it as compact as possible, but capable of insertion and retrieval.

This current example is meant to be specific to input where the key is "A-Z", but there could often be unexpected input such as "a", or "z", or "az". Therefore, the only reason a hash table is being used instead of an array of 26 elements, is to handle those exceptions. Performance of the buckets is not important, so building a linked list for collisions isn't tragic.

C Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /* Input Specifications Begin */
  6. #define MAX_KEY 20
  7. #define HT_WIDTH 26
  8. #define VAL_TYPE int
  9.  
  10. int hash(char *key) {
  11. int i=0;
  12. do{i+=*key+13;}while(*++key);
  13. return i%HT_WIDTH;
  14. }
  15. /* Input Specifications End */
  16.  
  17. /* Hash Table Begin */
  18. int ht_error;
  19. typedef struct ht_me {struct ht_me *next; char key[MAX_KEY]; VAL_TYPE value;} ht_b;
  20. ht_b *ht_table[HT_WIDTH];
  21. void ht_init() {
  22. int i;
  23. for(i=0;i<HT_WIDTH;i++)ht_table[i]=NULL;
  24. }
  25. void ht_insert(char *key, VAL_TYPE value) {
  26. int i=hash(key);
  27. ht_b *node;
  28. node = (ht_b *) malloc(sizeof( ht_b ));
  29. strcpy(node->key, key);
  30. node->value = value;
  31. node->next = ht_table[i];
  32. ht_table[i] = node;
  33. }
  34. int ht_lookup(char *key) {
  35. ht_error=0;
  36. int i=hash(key);
  37. ht_b *node;
  38. node = ht_table[i];
  39. while(node) {
  40. if(!strcmp(node->key,key))return node->value;
  41. node=node->next;
  42. }
  43. return ht_error=1;
  44. }
  45. void ht_clean_bucket(ht_b *node) {
  46. if(!node)return;
  47. ht_clean_bucket(node->next);
  48. free(node);
  49. }
  50. void ht_kill() {
  51. int i;
  52. for(i=0;i<HT_WIDTH;i++) {
  53. ht_clean_bucket(ht_table[i]);
  54. ht_table[i]=NULL;
  55. }
  56. }
  57. /* Hash Table End */
  58.  
  59. int main() {
  60. int value = 0;
  61. char key[3];
  62. key[2] = 0;
  63.  
  64. ht_init();
  65.  
  66. for(key[0]='A';key[0]<='Z';key[0]++)
  67. for(key[1]='A';key[1]<='Z';key[1]++)
  68. ht_insert(key, value++);
  69.  
  70. value = ht_lookup("ZZ");
  71. if(!ht_error) printf("%d\n", value);
  72. else printf("Key Does Not Exist\n");
  73.  
  74. ht_kill();
  75.  
  76. return 0;
  77. }

Last edited by Sane; Jan 8th, 2008 at 8:40 PM.
Sane is offline   Reply With Quote