summaryrefslogtreecommitdiff
path: root/src/02/04/hash.c
blob: 01942edca3d8985964935b2746a7b52aa3cd8c3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "hash.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int to_hash(int key)
{
  return key % 13;
}

Node *node_init()
{
  Node *node = malloc(sizeof(Node));
  node->next = NULL;
  node->value = NULL;
  return node;
}

Node *node_at(Node *head, int index)
{
  Node *current = head;

  for (int i = 0; i < index; i++)
    current = current->next;

  return current;
}

void node_inspect(Node *node)
{
  if (!node)
    return;

  int i = 0;
  while (node) {
    printf("[%d: %3d]", i, node->value);
    node = node->next;
    i++;
  }
  printf("\n");
}

Hash *hash_init(int buckets)
{
  Hash *hash = malloc(sizeof(Hash));
  hash->head = node_init();
  Node *current = hash->head;

  for (int i = 1; i < buckets; i++) {
    current->next = node_init();
    current = current->next;
  }
  return hash;
}

void *hash_get(Hash *hash, int key)
{
  int bucket = to_hash(key);
  Node *node = node_at(hash->head, bucket);
  node_inspect(hash->head);
  return node->value;
}

void hash_set(Hash *hash, int key, void *value)
{
  node_inspect(hash->head);
  int bucket = to_hash(key);
  Node *node = node_at(hash->head, bucket);
  node->value = value;
  node_inspect(hash->head);
}