//----------------------------------------------------------------------------- // HashTest.c // Demonstrates computation of hash codes, and probe sequences. // // compile: gcc -o HashTest HashTest.c // //----------------------------------------------------------------------------- #include #include #include #include #include typedef char* keyType; typedef uint64_t codeType; // print_binary_64() // Prints a hash code as a bit string void print_binary_64(codeType n) { for (int i = 63; i >= 0; i--) { printf("%d", (int)((n >> i) & 1)); if (i % 8 == 0 && i != 0) printf(" "); } printf("\n"); } // hash() // Returns the hash code for key k. codeType hash(keyType k) { codeType magicNumber1 = 0xcbf29ce484222325; codeType magicNumber2 = 0x100000001b3; codeType result = magicNumber1; codeType nextChar = *k; // get 1st char in k while( nextChar ) { // while not at end of k result ^= nextChar; // result = result (exor) nextChar result *= magicNumber2; // result = result * magicNumber2 nextChar = *(++k); // get next char } return result; } // probe() // Returns the ith term in the probe sequence for code. This function is denoted h(k,i), // and given in the Dictionary handout, second example in the hash table section. size_t probe(codeType code, size_t arr_size, size_t i){ codeType h1 = code & (arr_size-1); // code % arr_size codeType h2 = 2*(code & (arr_size/2 - 1)) + 1; // 2*(code % arr_size/2) + 1 return (h1 + i*h2) & (arr_size-1); // (h1 + i*h2) % arr_size } int main(void){ keyType A[] = {"one","two","three","four","five","six","seven","eight", "nine","ten","eleven","twelve","thirteen","fourteen", "fifteen","sixteen","seventeen","eighteen","nineteen", "twenty","twenty-one","twenty-two","twenty-three","twenty-four", "twenty-five","twenty-six","twenty-seven","twenty-eight", "twenty-nine"}; int i, j, slot, n=29; int tableSize = 8; codeType code; printf("\n"); printf("key : code : probe sequence\n"); printf("-----------------------------------------------------\n"); for( i=0; i