Skip to content

Instantly share code, notes, and snippets.

@colegleason
Created September 13, 2011 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save colegleason/1213291 to your computer and use it in GitHub Desktop.
Save colegleason/1213291 to your computer and use it in GitHub Desktop.
Hashmap
#include <stdio.h>
#include <string.h>
#define MAX_KEY 50
#define MAX_HASH 10
typedef struct node {
char key[MAX_KEY];
int value;
struct node *next;
} node;
int hash_func(char key[], int hash_max)
{
// Adds up char values of key and then does a modulus on the hash size
int total = 0;
int i, len;
len = strlen(key);
for(i = 0; i < len; i++)
{
total += (int) key[i];
}
return total % hash_max;
}
int put_int(node *hash_array[], int hash_max, char key[], int value)
{
// constructs a new node and puts it into the array at the head of the linked list
int index = hash_func(key, hash_max);
printf("Putting %s into hash at index %d\n", key, index);
node new;
new.value = value;
strcpy(new.key, key);
new.next = hash_array[index];
hash_array[index] = &new;
return 0;
}
int *get_int_ptr(node *hash_array[], int hash_max, char key[])
{
// goes through linked list at the index and outputs the int if it exists
int index = hash_func(key, hash_max);
node *curr = hash_array[index];
printf("Looking for %s in hash\n", key);
while(curr != NULL)
{
printf("At node with key %s and value %d\n", curr->key, curr->value);
if(strcmp(curr->key, key) == 0)
{
int *ans;
ans = &(curr->value);
return ans;
}
else {
curr = curr->next;
}
}
return NULL;
}
int init_hash(node *hash_array[], int hash_max)
{
//fills a hash array with empty structs
struct node empty;
empty.key[0] = '\0';
empty.value = 0;
empty.next = NULL;
int i;
for(i = 0; i++; i < hash_max)
{
hash_array[i] = &empty;
}
return 0;
}
int main()
{
//make and init hash array
node *hash_array[MAX_HASH];
init_hash(hash_array, MAX_HASH);
//put some values in. two and three go to same bucket
put_int(hash_array, MAX_HASH, "one", 1);
put_int(hash_array, MAX_HASH, "two", 2);
put_int(hash_array, MAX_HASH, "three", 3);
// get an int pointer back as answer
int *ans_ptr = get_int_ptr(hash_array, MAX_HASH, "two");
// make sure it isn't null
if(ans_ptr != NULL) {
int ans = *ans_ptr;
printf("%d\n", ans);
}
else {
printf("Not found\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment