Monday, July 03, 2006

Set Operations

Set Operations on Array
U - Universal Set
A - Subset
B - Subset

1. Union - All elements in A or B.
2. Intersection - All elements in A and B.
3. Minus - All elements in A but not in B.
4. Complement - All elements in U - A.

If the A, B, U are sorted
1. Union
Do a merge of A and B. If we get two elements with same value then take one of them and proceed.
i=0;
k=0;
j=0;
while(i lessThan n && j lessThan n)
{
_____if(A[i] lessThan B[j])
_____{
__________C[k] = A[i];
__________i++;
__________k++;
_____}
_____else if(A[i] greaterThan B[j])
_____{
__________C[k] = B[i];
__________j++;
__________k++;
_____}
_____else
_____{
__________C[k] = A[i];
__________j++;
__________k++;
__________i++;
_____}
}
while(i lessThan n)
{
__________C[k] = A[i];
__________i++;
__________k++;
}
while(j lessThan n)
{
__________C[k] = B[j];
__________j++;
__________k++;
}

2. Intersection
Normal Merge of A and B.
A[0,n-1] B[0,n-1]
Assuming that since these arrays represent sets we dont have any repeating elements
i=0;
k=0;
j=0;
while(k lessThan n && i lessThan n && j lessThan n)
{
_____if(A[i] == B[j])
_____{
__________print A[i];
__________i++;
__________j++;
__________k++;
_____}
_____else if(A[i] lessThan B[j])
_____{
__________i++;
_____}
_____else
_____{
___________j++;
_____}
}

3. Minus
C = A - B

while(k lessThan n && i lessThan n && j lessThan n)
{
_____if(A[i] == B[j])
_____{
__________i++;
__________j++;
_____}
_____else if(A[i] lessThan B[j])
_____{
__________C[k] = A[i];
__________k++;
__________i++;
_____}
_____else
_____{
___________j++;
_____}
}
if(j greaterThanEqualTo n)
{
_____while(k lessThan n && i lessThan n)
_____{
__________C[k]=A[i];
__________i++;
__________k++;
_____}
}

3. Complement
Same as Minus. complement(A) = U - A

No comments: