I have developed following program which takes two sets as input and
returns union and intersection set.
Code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
typedef struct set
{
int order;
int *ele;
};
/* Function Prototypes */
struct set _union(struct set, struct set);
struct set _isect(struct set, struct set);
void display(struct set);
void getdata(struct set*);
int main()
{
struct set s1, s2, s3, s4;
int i,j;
system("CLS");
printf("\nSET 1:\n");
getdata(&s1);
printf("\nSET 2:\n");
getdata(&s2);
s3 = _union(s1, s2);
system("PAUSE");
printf("\n\nThe union is:\n");
display(s3);
s4 = _isect(s1, s2);
printf("\nThe intersection is:\n");
display(s4);
system("PAUSE");
return 0;
}
/* display() : displays the set. */
void display(struct set t)
{
int i;
printf("\n{ ");
for(i=0; i<t.order; i++)
{
printf("%d",t.ele[i]);
if(i+1 != t.order)
printf(", ");
}
printf(" }");
}
/* getdata() : gets set data. */
void getdata(struct set* t)
{
int i;
printf("\nHow many elements: ");
scanf("%d",&t->order);
t->ele = (int*) malloc(sizeof(int)*t->order);
printf("\nEnter elements: \n");
for(i=0; i<t->order; i++)
{
scanf("%d",&t->ele[i]);
}
}
/* _union() : returns union of two sets */
struct set _union(struct set A, struct set B)
{
int i,j;
struct set C;
/*Maximum no of elements in union set of two set is sum of order of that
two sets */
C.ele = (int*) malloc(sizeof(int)*(A.order+B.order));
C = A; /* Copying first set into union set */
/* Elements in set B which are not in set A are copied to union set */
for(i=0; i<B.order; i++)
{
for(j=0; j<A.order; j++)
{
if(B.ele[i] == A.ele[j])
break;
else
continue;
}
if(j == A.order)
{
C.ele[C.order] = B.ele[i];
C.order++;
}
}
return(C);
}
/* _isect() : returns intersection of two sets */
struct set _isect(struct set A, struct set B)
{
int i,j,k,temp;
struct set C;
/*Maximum order of intersection set of two set is least order among that
two sets */
if(A.order > B.order)
temp = B.order;
else
temp = A.order;
C.ele = (int*) malloc(sizeof(int)* temp);
C.order = 0;
/* Elements which are common in both sets are copied into _isect set */
for(i=0; i<A.order; i++)
{
for(j=0; j<B.order; j++)
{
if(A.ele[i] == B.ele[j])
{
/* Check for avoiding multiple addition of number into set */
for(k=0; k<C.order; k++)
{
if(C.ele[k] == A.ele[i])
break;
else
continue;
}
if(k == C.order)
{
C.ele[C.order] = A.ele[i];
C.order++;
}
}
}
}
return(C);
}
this programs works well but i wonder if i can optimise functions _union() and _isect().
plz give me suggestion.