-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparseset.c
56 lines (49 loc) · 1.44 KB
/
sparseset.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
/* Implementation of sparse sets based on
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.30.7319
*
* Adapted from Dawid Weiss's implementation at
* https://github.com/carrotsearch/langid-java/blob/master/langid-java/src/main/java/com/carrotsearch/labs/langid/DoubleLinkedCountingSet.java
*
* Marco Lui, July 2014
*/
#include <stdlib.h>
#include "sparseset.h"
Set *alloc_set(size_t size){
Set *s;
if ( (void *)(s = (Set *) malloc(sizeof(Set))) == 0 ) exit(-1);
s->members=0;
if ( (void *)(s->sparse = (unsigned *) malloc(size * sizeof(unsigned))) == 0 ) exit(-1);
if ( (void *)(s->dense = (unsigned *) malloc(size * sizeof(unsigned))) == 0 ) exit(-1);
if ( (void *)(s->counts = (unsigned *) malloc(size * sizeof(unsigned))) == 0 ) exit(-1);
return s;
}
void free_set(Set * s){
free(s->sparse);
free(s->dense);
free(s->counts);
free(s);
}
void clear(Set *s) {
s->members = 0;
}
unsigned get(Set *s, unsigned key) {
unsigned index = s->sparse[key];
if (index < s->members && s->dense[index] == key) {
return s->counts[index];
}
else {
return 0;
}
}
void add(Set *s, unsigned key, unsigned val){
unsigned index = s->sparse[key];
if (index < s->members && s->dense[index] == key) {
s->counts[index] += val;
}
else {
index = s->members++;
s->sparse[key] = index;
s->dense[index] = key;
s->counts[index] = val;
}
}