#ifndef NULL
#define NULL (0)
#endif
typedef enum
{
NAME,
NUMBER,
BIRTHDAY,
EMAIL,
MEMO,
FIELD_END
} FIELD;
typedef struct
{
int count;
char str[20];
} RESULT;
const int MAXL = 20;
const int MAXR = 50000;
const int MAXE = 500;
const int KEYV = 10007;
inline int hash(const char* s)
{
int retVal = 0;
for (int i = 0; s[i] != NULL; ++i)
{
retVal += s[i];
retVal = (retVal << 3) - retVal;
while (retVal >= KEYV) retVal -= KEYV;
}
return retVal;
}
struct RECORD
{
int hash[FIELD_END];
char field[FIELD_END][MAXL];
};
RECORD rPool[MAXR];
int rCnt;
int hTable[FIELD_END][KEYV][MAXE];
int hCount[FIELD_END][KEYV];
inline void STRCPY(const char* src, char* dest)
{
for (int i = 0; dest[i] = src[i]; ++i);
}
inline int STRCMP(const char* a, const char* b)
{
int i;
for (i = 0; a[i] != NULL && b[i] != NULL && a[i] == b[i]; ++i);
return a[i] - b[i];
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void InitDB()
{
rCnt = 0;
for (int i = 0, j; i < FIELD_END; ++i) for (j = 0; j < KEYV; ++j) hCount[i][j] = 0;
}
void Add(char* name, char* number, char* birthday, char* email, char* memo)
{
RECORD* newR = &rPool[rCnt];
STRCPY(name, newR->field[NAME]);
STRCPY(number, newR->field[NUMBER]);
STRCPY(birthday, newR->field[BIRTHDAY]);
STRCPY(email, newR->field[EMAIL]);
STRCPY(memo, newR->field[MEMO]);
for (int i = 0; i < FIELD_END; ++i)
{
newR->hash[i] = hash(newR->field[i]);
hTable[i][newR->hash[i]][hCount[i][newR->hash[i]]++] = rCnt;
}
++rCnt;
}
int Delete(FIELD field, char* str)
{
int cnt = 0, h = hash(str), limit = hCount[field][h];
for (int i = 0, j; i < limit; ++i)
{
if (STRCMP(str, rPool[hTable[field][h][i]].field[field]) == 0)
{
RECORD& r = rPool[hTable[field][h][i]];
for (j = 0; j < FIELD_END; ++j) r.field[j][0] = NULL;
++cnt;
}
}
return cnt;
}
int Change(FIELD field, char* str, FIELD changefield, char* changestr)
{
int cnt = 0, h = hash(str), cH = hash(changestr), limit = hCount[field][h];
for (int i = 0; i < hCount[field][h]; ++i)
{
if (STRCMP(str, rPool[hTable[field][h][i]].field[field]) == 0)
{
RECORD& r = rPool[hTable[field][h][i]];
STRCPY(changestr, r.field[changefield]);
r.hash[changefield] = cH;
hTable[changefield][cH][hCount[changefield][cH]++] = hTable[field][h][i];
++cnt;
}
}
return cnt;
}
RESULT Search(FIELD field, char* str, FIELD ret_field)
{
int h = hash(str);
RESULT result = { 0, };
for (int i = 0; i < hCount[field][h]; ++i)
{
if (STRCMP(str, rPool[hTable[field][h][i]].field[field]) == 0 && ++result.count == 1)
{
STRCPY(rPool[hTable[field][h][i]].field[ret_field], result.str);
}
}
return result;
}
댓글