ããã·ã¥ãã¼ãã«ãä½ã£ã¦ã¿ã¦ããã£ããã¨
Cè¨èªã¯ã½ã¼ã¹è²¼ã£ã¦ã試ãã®ããã©ãããªãã¨ãæã£ããã ãã©ãããèããã¨CodePad ã«è²¼ãã°è¨äºãè¦ã人ãããå®è¡ã§ããã¨ãæã£ãã®ã§æ©éãã£ã¦ã¿ãã
以ä¸æã£ããã¨ã
ããã·ã¥ãã¼ãã«ã«å ¥ããvalueãã©ãããåã«ãããè¿·ã
ããã¯Cã使ãã¨ãã«ã¯ãã¤ãè¿·ãã
æåã¯void*ã«ãã¦ã確ä¿ã¨éæ¾ã¯ã¦ã¼ã¶ã®è²¬ä»»ã¨ãããã¨ã«ãããã§ãåç´ã«ãã¤ã³ã¿åã«ããã¨ãæååãvalueã«å
¥ãããããã®ã¯ç°¡åã«ãªããã©ãããã·ã¥ãã¼ãã«ã使ã£ã¦ã¯ã¼ãã«ã¦ã³ãã£ã³ã°ãããã¨ããããããã®ããããé¢åã«ãªãã
éã«intããå
¥ããªãããã·ã¥ãã¼ãã«ã¨ãå¯ãã
templateã欲ãããªããã©ãC++使ããªãããããããã·ã¥ãã¼ãã«ãªãä½ãå¿
è¦ã¯ãªãã
çµå±ãvalueã¯åã¿ã°ã¨intããvoid*ãããå
¥ãå
±ç¨ä½ããã£ã¤ããæ§é ä½ã¨ãã¦ãé©åãªåã®åºãå
¥ãã¯ã¦ã¼ã¶å´ã®è²¬ä»»ã¨ãããã¨ã«ããããã¨intãããã¤ã³ã¿ã¨ãã¦set/getãããããªã¡ã½ãããä½ã£ã¦æ¥½ã«åºãå
¥ãã§ããããã«ã
enum val_type { H_NIL, H_INT, H_CHAR, H_LONG, H_DOUBLE, H_PTR }; typedef struct val_t { enum val_type type; union { int n; char ch; long l; double d; void* pt; } val; } val_t; HASH hash_set(HASH me, const char* key, val_t val); HASH hash_set_i(HASH me, const char* key, int val); ... HASH hash_set_p(HASH me, const char* key, void* val); val_t hash_get(HASH me, const char* key); int hash_get_i(HASH me, const char* key); ... void* hash_get_p(HASH me, const char* key);
使ãã¨ãã¯ããã
HASH h = hash_create(); hash_change_func(h, func); for( i=0; i<NUM; i++ ){ sprintf(key, "key%d", i); /* ç´æ¥ intå¤ãå ¥ãããã¨ãã§ãã */ hash_set_i(h, key, i); /* ç´æ¥ intå¤ãåãåºãã */ assert(i == hash_get_i(h, key)); } hash_delete(h);
ããã·ã¥é¢æ°ã«ããæ§è½ã大ããå·¦å³ããã
http://codepad.org/Bybm7P8I ã®å®è¡çµæãè¦ãã¨åãããã©ã
unsigned int fucked_hash(const char* key, int mod){ unsigned char val; if(!key){ return 0; } if(*key == '\0'){ return 0; } val = (unsigned char)(*key) % mod; return ( val + fucked_hash(key+1, mod) ) % mod; }
ããã·ã¥é¢æ°ããã®ãããªããå æ¸ãªå®è£ ã«ããã¨æ§è½ãèããå£åãããã¨ã«ããè¡çªãå¤ããªãã®ã§ãä»åã®ããã«è¡çªãé£éæ³ã§åé¿ãã¦ããå®è£ ã§ã¯é£éã®æ·±ãã大å¤æ·±ããªã£ã¦ã²ã©ããã¨ã«ãªããç¹ã«ãã®å®è£ ã§ã¯ãããã·ã¥å¤ãé常ã«å°ããå¤ã«ãªããããã®ã§ãããã·ã¥ãã¼ãã«ã大ãããã¦ãè¡çªãæ¸ããªãã£ããããã
ãã¨ãããã·ã¥é¢æ°ã¨ã¹ããããµã¤ãºã®ç¸æ§ã«ãã£ã¦ã¯ããã¡ããã¡ãæ§è½ãæªåããã
ææªãªä¾ã®ä¸ã¤ããcharé
åã256é²æ°ã®å¤åé·æ´æ°ã¨èããä¸ã§ãã¹ããããµã¤ãºã2ã®ããä¹ã«ãã¦ãã¾ã£ãå ´åã ãããèããã°ããããã©ãããã¯ä¾ãã°ã¹ããããµã¤ãºã65536ã§ããã¨ãããã¼ã®å
é 2byte(å®è£
ã«ãã£ã¦ã¯æ«å°¾2byte)以å¤ãç¡è¦ãã¦2byteåãã使ããªãã®ã¨åããã¨ã§ãããã¨ã¦ã¤ããªãè¡çªãçºçããã
charé
åã256é²æ°ã¨ããå ´åã§ãã¹ããããµã¤ãºãç´ æ°ã§ããã°ãããªãã«åæ£ããããã¾ãéã«charé
åãä½ããã®ã¡ãã£ã¨å¤§ããªç´ æ°åºæ°(ä¾ãã°977é²æ°ã¨ã)ã¨èããã¨ã¹ããããµã¤ãºã2ã®ããä¹ã§ãã¡ããã¨æ§è½ãã§ãã
ããã«ç´°ãããã¨ãè¨ãã¨ãcharé
åãç´ æ°åºæ°ã¨ãã¦ã¹ããããµã¤ãºã2ã®ããä¹ã«ããå ´åã®åºæ°ã¯ãä¾ãã°
ã®ãããª2ã®ããä¹+1ã«ãªããããªç´ æ°ã¯å
·åãæªã(2ã®ããä¹ã§å°ä½ãåãã¨1ã«ãªãããã)ã
ã¾ãå®éã«ã¯ã¹ãããæ°ã¯ç´ æ°ã«ãã¦ããã¦ãããã·ã¥é¢æ°ãå¤å°éæãã§ããã·ã«ãã¦ããã®ãå®è·µçã ããã
ãã®ããã«ãããã·ã¥ãã¼ãã«ã£ã¦å®è£ ã®è³ªã«ä¾åãã¦çµæ§ãã¼ãã¼ãªã®ã§(ã¾ãåã®å®è£ ãæªãã ããããããªããã©)ãå®ã¯ç¾å®çã«ã¯ãã¤ããªããªã¼ã®ã»ããæ§è½ã®ãã©ã³ã¹/å®å®æ§ãããã£ããããªãã®ããªãå®éã®ã¨ãããO(1)>>>>>>>O(logn) ã«ãªããããªæ¥µç«¯ã«å·¨å¤§ãªè¦ç´ æ° n ãæ ¼ç´ã§ãããããªãã©ãããªã¡ã¢ãªã確ä¿ã§ãããã ãããã