/* * hashtable.c * * Computer Science 50, Fall 2011 * section7 * * Credit: Tommy MacWilliam (aka TMac) * * Create your very own hash table. */ #include #include #include #include // size of hashtable #define SIZE 5 // function prototype int hash_function(char *key); int main(void) { // create a hash table char *hash_table[SIZE]; // initalize the hash table with empty strings for (int i = 0; i < SIZE; i++) hash_table[i] = ""; // put a sample key into the hash table int v = hash_function("CS50"); hash_table[v] = "CS50"; // declare a choice value char *choice; while(strcmp(choice, "quit") != 0) { // get user's choice printf("What do you want to do? "); choice = GetString(); // print out all keys in the hash table if (strcmp(choice, "print") == 0) for (int j = 0; j < SIZE; j ++) printf("%d: %s\n", j, hash_table[j]); /* put a key into the table (Quick Quiz: how fast is this, asymptotically? */ else if (strcmp(choice,"insert") == 0) { printf("Key please: "); string s = GetString(); hash_table[hash_function(s)] = s; } /* get a key from the table (Quick Quiz: how fast is this, asymptotically? */ else if (strcmp(choice, "lookup") == 0) { printf("Key please: "); string s = GetString(); if (strcmp(hash_table[hash_function(s)], s) == 0) printf("It's here!\n"); else printf("Couldn't find it.\n"); } } // success! return 0; } /* * Maps a key to a value. */ int hash_function(char *key) { // initalize hash variable int hash = 0; /* calculate specific hash value (Quick Quiz: what is my hash function?) */ for (int i = 0, n = strlen(key); i < n; i++) hash += key[i]; // return a value return hash % SIZE; }