Chitika

Showing posts with label algorithm sets difference union intersection. Show all posts
Showing posts with label algorithm sets difference union intersection. Show all posts

Thursday, May 16, 2013

Sets Difference algorithm

Lets assume you have two sets as follows:

example sets:

Set A

1
2
3
4

Set B

3
4
5
6

now we want to get difference of these sets:

(assume a cleared (0) flag "added" for each element of set B)

algorithm:

1. for each element E in set B, iterate over elements in set A
    i. if value of element E is found in set A, remove that entry from A
   ii. if value of element E is not found in set A, set (1) "added" flag of element E
4. Remaining elements in set A, represents set difference A-B
5. elements in set B, having flag "added" set (1), represents set difference B-A
6. elements in set B, having flag "added" cleared(0), represents set intersections
7. All remaining elements in set A and value of all elements in set B represents union of set A and B

result:

Set A

1
2

Set B

3
4
5 -> added
6 -> added

A-B = 1,2
B-A = 5,6

A intersection B = 3,4
A union B = 1,2,3,4,5,6

optimizations:

if set A is sorted, iterated over elements of set A, until element value in set A is less than element E of set B
similarly, further optimizations are possible when both sets are sorted.