-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.c
131 lines (105 loc) · 1.96 KB
/
set.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "set.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <openssl/md5.h>
struct set_ {
uint16_t *data;
size_t sz;
size_t cap;
};
// Seems like a good default?
enum { DEFAULT_HASH_CAPACITY = 8 };
// 75% seems like a good idea?
static const double LOAD_FACTOR = 0.75;
set *set_create(void)
{
set *s = malloc(sizeof(*s));
if (!s) {
return NULL;
}
s->sz = 0;
s->cap = DEFAULT_HASH_CAPACITY;
s->data = calloc(s->cap, sizeof(*s->data));
return s;
}
bool set_add(set * s, uint16_t id)
{
if (!s) {
return false;
}
if (1.0 * s->sz / s->cap > LOAD_FACTOR) {
set *new_set = set_create();
new_set->cap = 2 * s->cap;
free(new_set->data);
new_set->data = calloc(new_set->cap, sizeof(*new_set->data));
if (!new_set->data) {
set_destroy(new_set);
return false;
}
for (size_t n = 0; n < s->cap; ++n) {
if (s->data[n]) {
set_add(new_set, s->data[n]);
}
}
free(s->data);
s->data = new_set->data;
s->cap = new_set->cap;
free(new_set);
}
size_t idx = id % s->cap;
// PROBING
while (s->data[idx]) {
if (s->data[idx] == id) {
// Good arguments for true or false return in this case;
// using false to indicate "did not insert" vs.
// using true to indicate "item is now in set"
return false;
}
++idx;
idx %= s->cap;
}
s->data[idx] = id;
if (s->data[idx]) {
s->sz++;
}
return s->data[idx] != 0;
}
bool set_contains(const set * s, uint16_t id)
{
if (!s) {
return false;
}
size_t idx = id % s->cap;
while (s->data[idx]) {
if (s->data[idx] == id) {
return true;
}
++idx;
idx %= s->cap;
}
return false;
}
void set_destroy(set * s)
{
if (!s) {
return;
}
for (size_t n = 0; n < s->cap; ++n) {
}
free(s->data);
free(s);
}
// used for debugging purposes; also used with recommend_removal function
void print_set(set * s)
{
if (!s) {
return;
}
for (size_t n = 0; n < s->cap; n++) {
if (s->data[n] != 0) {
printf("#%u \n", s->data[n]);
}
}
puts("\n");
}