#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char* key;
char* val;
}el;
el* el_new( char* key, char* val);
typedef struct{
int size;
int step;
int count;
el** data;
int* keys;
}ht;
ht* ht_new( int size );
ht* ht_inc( ht* h );
ht* ht_add( ht* h, char* key, char* val );
int ht_idx( ht* h, char* key );
int ht_has( ht* h, int idx );
int ht_hsh( ht* h, char* key, int step);
char* ht_get( ht* h, char* key );
el* el_new( char* key, char* val){
el* e = ( el* )malloc ( sizeof( el ) );
e->key = ( char* ) malloc( strlen( key ) * sizeof(char) );
e->val = ( char* ) malloc( strlen( val ) * sizeof(char) );
strcpy(e->key, key);
strcpy(e->val, val);
return e;
}
ht* ht_new( int size ){
ht* h = (ht*) malloc ( sizeof(ht));
h->size = size;
h->step = 7;
h->count = 0;
h->data = (el**)malloc( h->size * sizeof( el* ) );
h->keys = (int*)malloc( h->size * sizeof(int) );
}
ht* ht_inc( ht* h ){
ht* nh = ht_new( h->size*2 );
int i;
for( i = 0; i < h->count; i++ ){
int k = ht_idx( nh, h->data[ h->keys[i] ]->key );
nh->keys[ i ] = k;
nh->data[ k ] = h->data[ h->keys[i] ];
nh->count++;
}
return nh;
}
int ht_has( ht* h, int idx ){
int i;
for( i = 0; i < h->count; i++ ) if( h->keys[i] == idx) return 1;
return 0;
}
int ht_idx( ht* h, char* key ){
int i, step = 0;
do i = ht_hsh( h, key, step++ );
while( ht_has( h, i ) );
return i;
}
ht* ht_add( ht* h, char* key, char* val ){
if(h->count == h->size ) h = ht_inc( h );
int i = ht_idx( h, key );
h->keys[ h->count ] = i;
h->data[ i ] = el_new( key, val );
h->count++;
return h;
}
char* ht_get( ht* h, char* key ){
int i, step = 0;
do i = ht_hsh( h, key, step++ );
while( strcmp(h->data[ i ]->key, key) != 0);
return h->data[ i ]->val;
}
int ht_hsh( ht* h, char* key, int step){
int sum = 0, i=0, max = strlen(key);
for(; i<max; i++) sum += (int)key[i];
return ( sum + step * h->step ) % h->size;
}
int main(){
ht* h = ht_new(2);
h = ht_add(h, "aaa","mama");
h = ht_add(h, "bbb","papa");
h = ht_add(h, "ccc","deda");
h = ht_add(h, "aab","baba");
printf("%s = %s\n","aaa",ht_get(h,"aaa"));
printf("%s = %s\n","bbb",ht_get(h,"bbb"));
printf("%s = %s\n","ccc",ht_get(h,"ccc"));
printf("%s = %s\n","aab",ht_get(h,"aab"));
return 0;
}