Created
November 27, 2011 02:55
-
-
Save lazypower/1396858 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
int hash_string(char str_name[]); | |
int main() | |
{ | |
int pass, slen, spos, hash_value; | |
char hash_str[9]; | |
char hash_table[64][9]; | |
int collisions = 0; | |
// init hash table | |
for ( pass = 0; pass < 64; pass++) | |
{ | |
hash_table [ pass ][0] = '\0'; | |
} | |
// porudce 64 strings to be hashed | |
for ( pass = 0; pass < 64; pass ++) | |
{ | |
// generate random string of 5 to 8 chars | |
slen = 5 + rand() % 4; | |
spos = 0; | |
do | |
{ | |
hash_str[ spos ] = 'A' + rand() % 25; | |
spos++; | |
slen--; | |
} while ( slen != 0 ); | |
hash_str[ spos ] = '\0'; | |
//display the string and its hash value | |
if ( 0 == pass % 4 ) | |
{ | |
cout << endl; | |
} | |
cout << hash_str << ", " ; | |
hash_value = hash_string ( hash_str ); | |
cout << hash_value << "\t"; | |
// check for collision | |
if ( '\0' == hash_table[ hash_value ] [0] ) | |
{ | |
strcpy( hash_table[ hash_value ], hash_str ); | |
} else { | |
collisions++; | |
} | |
} | |
cout << endl; | |
cout << "There were " << collisions < " collisions. " << endl; | |
return EXIT_SUCCESS; | |
} | |
int hash_string(char str_name[]) | |
{ | |
int hashval; | |
hashval = str_name[ 0 ]; | |
hashval ^= str_name[ strlen( str_name ) / 2 ]; | |
hashval += str_name[ strlen( str_name ) - 1 ]; | |
return ( hashval & 0x3f ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment