2016年1月7日 星期四

Search a lot of string by Hash

感謝Bruce提供
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_COUNTRYCODE_SIZE 3
#define HASH_SIZE MAX_COUNTRYCODE_SIZE+1
int countrycode_hashtable[HASH_SIZE];

struct data
{
    unsigned char name[10];
};
 
struct data country_code_table[MAX_COUNTRYCODE_SIZE]={
    {"john"},{"tom"},{"wow"}
};

unsigned long hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + c;

    return hash;
}

void init_countrycode_hashtable()
{
    int i, j;

    memset(countrycode_hashtable, 0, sizeof(countrycode_hashtable));
    for (i = 0; i < MAX_COUNTRYCODE_SIZE; i++) {
        j = hash((unsigned char *)country_code_table[i].name)%(HASH_SIZE);
        printf("[%d] hash = %d\n", i, j); 
        if (countrycode_hashtable[j] == 0)
            countrycode_hashtable[j] = 1;
        else
            printf("[%d] Collision hash = %d\n", i, j); 
    }   
}

void test(char *string)
{
    int j;
    j = hash((unsigned char *)string)%(HASH_SIZE);
    if (countrycode_hashtable[j]) {
        printf("match: %s\n", string);
    }   
}

int main()
{
    init_countrycode_hashtable();
    test("wow");
    return 0;
}
結果:
[0] hash = 0
[1] hash = 1
[2] hash = 2
match: wow

沒有留言:

張貼留言