-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.c
130 lines (108 loc) · 2.27 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
#include "tree.h"
#include "set.h"
void add(int value, void *arg1, void *arg2);
void add_if_in_other(int value, void *arg1, void *arg2);
void add_if_not_in_other(int value, void *arg1, void *arg2);
void print(int value, void *arg1, void *arg2);
void count(int element, void *arg1, void *arg2);
struct set
{
node_t *root;
};
set_t *set_new()
{
return calloc(1, sizeof(set_t));
}
void set_free(set_t *s)
{
// FIXME
}
void set_add(set_t *s, int value)
{
node_add(&(s->root), value);
}
bool set_contains(set_t *s, int value)
{
return node_contains(&(s->root), value);
}
void add(int value, void *arg1, void *arg2)
{
set_add((set_t *)arg1, value);
}
void add_if_in_other(int value, void *arg1, void *arg2)
{
set_t *other = arg1;
set_t *result = arg2;
if (set_contains(other, value))
{
set_add(result, value);
}
}
void add_if_not_in_other(int value, void *arg1, void *arg2)
{
set_t *other = arg1;
set_t *result = arg2;
if (set_contains(other, value) == false)
{
set_add(result, value);
}
}
set_t *set_union(set_t *s1, set_t *s2)
{
set_t *result = set_new();
node_forall(s1->root, add, result, NULL);
node_forall(s2->root, add, result, NULL);
return result;
}
set_t *set_intersection(set_t *s1, set_t *s2)
{
set_t *result = set_new();
node_forall(s1->root, add_if_in_other, s2, result);
return result;
}
set_t *set_subtraction(set_t *s1, set_t *s2)
{
set_t *result = set_new();
node_forall(s1->root, add_if_not_in_other, s2, result);
return result;
}
void print(int value, void *arg, void *IGNORE2)
{
int *size = arg;
if (*size > 0)
{
printf("%d, ", value);
}
else
{
printf("%d", value);
}
*size = *size - 1;
}
void set_print(set_t *s)
{
printf("{");
int size = set_size(s) - 1;
node_forall(s->root, print, &size, NULL);
printf("}");
}
bool set_equal(set_t *s1, set_t *s2)
{
if (set_size(s1) != set_size(s2)) return false;
set_t *s3 = set_subtraction(s1, s2);
bool result = (set_size(s3) == 0);
set_free(s3);
return result;
}
void count(int element, void *arg1, void *arg2)
{
int *size = arg1; // alt. ++((int *)arg);
++*size;
}
int set_size(set_t *s)
{
if (s->root == NULL) return 0;
int size = 0;
node_forall(s->root, count, &size, NULL);
return size;
}