You are asked to give a static implementation of the ADT set having the following functions:
- void toempty(SET *S)
- int empty(SET S)
- int find(int x, SET S)
- void add(int x, SET *S)
- void removeS(int x, SET *S)
- void intersect(SET S1, SET S2, SET *R)
- void unionS(SET S1, SET S2, SET *R)
- void complement(SET S, SET *R)
- void display(SET S)
Difficulty level
![](images/star2.png)
This exercise is mostly suitable for students
#include <stdio.h>
#define N 100
typedef struct
{
int nbr;
int tab[N];
} SET;
void toempty(SET *e)
{
e->nbr = 0;
}
int empty(SET e)
{
return e.nbr == 0;
}
int find(int x, SET e)
{
int i = 0;
while (i < e.nbr && e.tab[i] != x)
i++;
return i < e.nbr;
}
void add(int x, SET *e)
{
if ( ! find(x, *e))
e->tab[e->nbr++] = x;
}
void removeS(int x, SET *e)
{
int i = 0;
while (i < e->nbr && e->tab[i] != x)
i++;
if (i < e->nbr)
e->tab[i] = e->tab[--e->nbr];
}
void intersect(SET e1, SET e2, SET *r)
{
int i, x;
toempty(r);
for (i = 0; i < e1.nbr; i++)
{
x = e1.tab[i];
if (find(x, e2))
add(x, r);
}
}
void unionS(SET e1, SET e2, SET *r)
{
int i;
*r = e2;
for (i = 0; i < e1.nbr; i++)
add(e1.tab[i], r);
}
void complement(SET e, SET *r)
{
int i, k;
for (i = 0; i < N; i++)
r->tab[i] = i;
for (i = 0; i < e.nbr; i++)
r->tab[e.tab[i]] = -1;
k = 0;
for (i = 0; i < N; i++)
if (r->tab[i] >= 0)
r->tab[k++] = r->tab[i];
r->nbr = k;
}
void display(SET e)
{
int i;
printf("[ ");
for (i = 0; i < e.nbr; i++)
printf("%d ", e.tab[i]);
printf("]");
}
int main()
{
SET a, b, c;
int i;
toempty(&a);
for (i = 0; i < 32; i += 2)
add(i, &a);
for (i = 30; i >= 0; i -= 3)
add(i, &a);
printf(" a : ");
display(a);
printf("\n");
toempty(&b);
printf("a empty? %s\n", empty(a) ? "yes" : "no");
printf("b empty? %s\n", empty(b) ? "yes" : "no");
for (i = 0; i < 32; i += 5)
add(i, &b);
printf(" b : ");
display(b);
printf("\n");
complement(b, &c);
printf(" ~b : ");
display(c);
printf("\n");
intersect(a, b, &c);
printf("a.b : ");
display(c);
printf("\n");
unionS(a, b, &c);
printf("a+b : ");
display(c);
printf("\n");
for (i = 0; i < 32; i += 3)
removeS(i, &c);
printf("c : ");
display(c);
printf("\n");
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
![](images/star3.png)