hashmap c

A hashmap in C is a data structure that allows for efficient storage and retrieval of key-value pairs. It is also known as a hash table or associative array. The hashmap uses a hash function to convert the key into an index in an array, where the corresponding value is stored.

To implement a hashmap in C, you can start by defining a struct to represent the key-value pair:

typedef struct {
    int key;
    int value;
} Entry;

Next, you need to define the hashmap itself, which is an array of buckets. Each bucket can hold multiple key-value pairs, so you can use a linked list to handle collisions:

#define NUM_BUCKETS 100

typedef struct Node {
    Entry entry;
    struct Node* next;
} Node;

typedef struct {
    Node* buckets[NUM_BUCKETS];
} HashMap;

To insert a key-value pair into the hashmap, you first calculate the hash value of the key using a hash function. Then, you insert the entry into the appropriate bucket based on the hash value:

void hashmap_insert(HashMap* map, int key, int value) {
    int hash = hash_function(key);
    int bucket_index = hash % NUM_BUCKETS;

    Node* new_node = malloc(sizeof(Node));
    new_node->entry.key = key;
    new_node->entry.value = value;
    new_node->next = NULL;

    Node* current = map->buckets[bucket_index];
    if (current == NULL) {
        map->buckets[bucket_index] = new_node;
    } else {
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new_node;
    }
}

To retrieve a value from the hashmap, you perform a similar process. Calculate the hash value of the key, find the bucket, and then traverse the linked list to find the matching key:

int hashmap_get(HashMap* map, int key) {
    int hash = hash_function(key);
    int bucket_index = hash % NUM_BUCKETS;

    Node* current = map->buckets[bucket_index];
    while (current != NULL) {
        if (current->entry.key == key) {
            return current->entry.value;
        }
        current = current->next;
    }

    // Key not found
    return -1;
}

Remember to implement a suitable hash function that distributes the keys evenly across the buckets to ensure efficient retrieval.

This is a basic implementation of a hashmap in C. Depending on the specific requirements of your application, you may need to add more functionality, such as resizing the hashmap when it becomes too full or handling collisions in a different way.