-
-
Save robertseaton/1214597 to your computer and use it in GitHub Desktop.
Hashmap
This file contains 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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define MAX_KEY 50 | |
#define MAX_HASH 10 | |
struct node { | |
char key[MAX_KEY]; | |
int value; | |
struct node* next; | |
}; | |
/* Adds up char values of key and then does a modulus on the hash size */ | |
int hash_func (char key[], int hash_max) | |
{ | |
int total = 0; | |
int len; | |
len = strlen(key); | |
int i; | |
for (i = 0; i < len; i++) | |
total += (int) key[i]; | |
return total % hash_max; | |
} | |
/* constructs a new node and puts it into the array at the head of the linked list */ | |
int put_int (struct node* hash_array[], int hash_max, char key[], int value) | |
{ | |
int index = hash_func(key, hash_max); | |
struct node* new = malloc(sizeof(struct node)); | |
printf("Putting %s into hash at index %d\n", key, index); | |
new->value = value; | |
strcpy(new->key, key); | |
new->next = hash_array[index]; | |
hash_array[index] = new; | |
return 0; | |
} | |
/* goes through linked list at the index and outputs the int if it exists */ | |
int* get_int_ptr (struct node* hash_array[], int hash_max, char key[]) | |
{ | |
int index = hash_func(key, hash_max); | |
struct 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; | |
} | |
/* fills a hash array with empty structs */ | |
int init_hash (struct node* hash_array[], int hash_max) | |
{ | |
struct node* empty = malloc(sizeof(struct node)); | |
empty->key[0] = '\0'; | |
empty->value = 0; | |
empty->next = NULL; | |
int i; | |
for (i = 0; i < hash_max; i++) | |
hash_array[i] = empty; | |
return 0; | |
} | |
int main () | |
{ | |
/* make and init hash array */ | |
struct 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