3 * gcc test1.c htable.c -o test1 -Wall -W -Wextra -ansi -pedantic
10 #include <time.h> /* for time() in srand() */
14 /* Function prototypes */
15 unsigned int myhashf(const void *key
);
16 int mystrcmp(const void *arg1
, const void *arg2
);
17 void myprintf(const void *key
, const void *data
);
18 void print_elm(void *data
);
19 void get_rand_string(char *str
, size_t len
);
25 char str
[20][10+1]; /* +1 for '\0' */
27 /* Initialize random number generator */
30 /* Produce some random strings to put in hash table */
31 for (i
= 0; i
< sizeof str
/ sizeof *str
; i
++)
32 get_rand_string(str
[i
], 10);
34 /* Initialize table */
35 if (htable_init(&htable
, 32, 2, myhashf
, mystrcmp
, myprintf
) == HT_NOMEM
) {
40 /* Add random entries in hash table */
41 for (i
= 0; i
< sizeof str
/ sizeof *str
; i
++)
42 htable_insert(&htable
, str
[i
], str
[i
]);
43 /* htable_print(&htable); */
46 * Traverse all elemets and print each one of them
47 * using the print_elm() callback function
49 htable_traverse(&htable
, print_elm
);
52 * Print the length of every chain
53 * This gives as a metric on how good or bad our hash function is
55 for (i
= 0; i
< htable_get_size(&htable
); i
++)
56 printf("chain[%lu] = %lu\n",
58 (unsigned long)htable_stat_get_chain_len(&htable
, i
));
60 /* Print number of automatic resizes */
61 printf("Automatic resizes: %lu\n", (unsigned long)htable_stat_get_grows(&htable
));
69 unsigned int myhashf(const void *key
)
71 unsigned int i
, hash
= 5381;
72 char *str
= (char *)key
;
74 for (i
= 0; i
< strlen(str
); i
++)
75 hash
= ((hash
<< 5) + hash
) + str
[i
];
80 int mystrcmp(const void *arg1
, const void *arg2
)
82 return (strcmp((char *)arg1
, (char *)arg2
));
85 void myprintf(const void *key
, const void *data
)
87 printf("%s(%s) ", (char *)key
, (char *)data
);
90 void print_elm(void *data
)
92 printf("%s\n", (char *)data
);
95 void get_rand_string(char *str
, size_t len
)
99 for (i
= 0; i
< len
; i
++)
100 str
[i
] = 65 + 32 + (rand() / (RAND_MAX
/ 26 + 1)); /* 'a' to 'z' */