Hashmap
This commit is contained in:
parent
f5f0d6328c
commit
975c010a2c
@ -2,6 +2,8 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include "hashmap.h"
|
||||||
|
|
||||||
#define INITIAL_BUFFER_SIZE 2
|
#define INITIAL_BUFFER_SIZE 2
|
||||||
|
|
||||||
char *input_buffer;
|
char *input_buffer;
|
||||||
|
44
c/lib/hashmap.h
Normal file
44
c/lib/hashmap.h
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
#define AOC_HASHMAP_RADIX 1024
|
||||||
|
|
||||||
|
int aoc_hash(const char *string) {
|
||||||
|
int len = strlen(string);
|
||||||
|
int hash = 1;
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
hash *= 7;
|
||||||
|
hash += string[i] * 13;
|
||||||
|
hash %= AOC_HASHMAP_RADIX;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef struct AocHashmapNode AocHashmapNode;
|
||||||
|
|
||||||
|
typedef struct AocHashmapNode {
|
||||||
|
char *key;
|
||||||
|
long value;
|
||||||
|
AocHashmapNode *next;
|
||||||
|
} AocHashmapNode;
|
||||||
|
|
||||||
|
typedef struct AocHashmap {
|
||||||
|
AocHashmapNode* buckets[AOC_HASHMAP_RADIX];
|
||||||
|
} AocHashmap;
|
||||||
|
|
||||||
|
AocHashmapNode *aoc_hashmap_get(AocHashmap *map, char *key) {
|
||||||
|
int hash = aoc_hash(key);
|
||||||
|
AocHashmapNode *node = map->buckets[hash];
|
||||||
|
while (node != NULL && strcmp(node->key, key) != 0) node = node->next;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
void *aoc_hashmap_put(AocHashmap *map, char *key, long value) {
|
||||||
|
int hash = aoc_hash(key);
|
||||||
|
AocHashmapNode *node = map->buckets[hash];
|
||||||
|
while (node != NULL) node = node->next;
|
||||||
|
map->buckets[hash] = malloc(sizeof(AocHashmapNode));
|
||||||
|
node = map->buckets[hash];
|
||||||
|
node->key = malloc(strlen(key) + 1);
|
||||||
|
strcpy(node->key, key);
|
||||||
|
node->value = value;
|
||||||
|
node->next = NULL;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user