Hsue66 / Algo

0 stars 0 forks source link

hash+open #11

Open Hsue66 opened 4 years ago

Hsue66 commented 4 years ago

/*#include using namespace std;

define MAX 1009

define LEN 10

void ztrcpy(char dst, char src) { while (dst++ = src++); }

int ztrcmp(char s1, chars2) { int c = 0; while (s1[c] != '\0') { if (s1[c] != s2[c]) break; c++; } return s1[c] - s2[c]; }

int hashTB[MAX]; char DB[MAX][LEN]; int dbsize;

void init() { for (int i = 0; i < MAX; i++) hashTB[i] = -1; }

unsigned int getHash(char str) { unsigned int hash = 5381; int c = 0; while (c = str++) hash = ((hash << 5) + hash + c) % MAX; return hash % MAX; }

void addtoHash(char *str, int dbidx) { int hash = getHash(str); for (int i = 0; i < MAX; i++) { if (hashTB[hash] == -1 || hashTB[hash] == MAX) { hashTB[hash] = dbidx; cout << hash<<": "<<hashTB[hash] << endl; break; } hash = (hash + 1) % MAX; } }

int findfromHash(char *str) { int hash = getHash(str); for (int i = 0; i < MAX; i++) { if (hashTB[hash] == -1) break; if (ztrcmp(DB[hashTB[hash]], str) == 0) return hashTB[hash]; hash = (hash + 1) % MAX; } return -1; }

void deletefromHash(char *str) { int hash = getHash(str); for (int i = 0; i < MAX; i++) { if (hashTB[hash] == -1) break; if (ztrcmp(DB[hashTB[hash]], str) == 0) { hashTB[hash] = MAX; cout << hash <<": "<<hashTB[hash] << endl; break; } hash = (hash + 1) % MAX; } }

int main() { init(); dbsize = 0; ztrcpy(DB[dbsize], (char)"hello"); addtoHash(DB[dbsize], dbsize); dbsize++; ztrcpy(DB[dbsize], (char)"hel"); addtoHash(DB[dbsize], dbsize); dbsize++; ztrcpy(DB[dbsize], (char)"hello"); addtoHash(DB[dbsize], dbsize); dbsize++; cout << endl; cout << findfromHash((char)"hello") << endl; cout<<findfromHash((char)"hl")<<endl; cout << findfromHash((char)"hel") << endl; cout << endl; deletefromHash((char)"hl"); deletefromHash((char)"hello"); cout << endl; ztrcpy(DB[dbsize], (char)"hello"); addtoHash(DB[dbsize], dbsize); dbsize++; ztrcpy(DB[dbsize], (char)"hello"); addtoHash(DB[dbsize], dbsize); dbsize++; } */