Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate difference between two sets in C?

Tags:

c

algorithm

set

I have two arrays, say A and B with |A|=8 and |B|=4. I want to calculate the set difference A-B. How do I proceed? Please note that there are no repeated elements in either of the sets.

Edit: Thank you so much everybody for a myriad of elegant solutions. Since I am in prototyping stage of my project, for now I implemented the simplest solution told by Brian and Owen. But I do appreciate the clever use of data structures as suggested here by the rest of you, even Though I am not a computer scientist but an engineer and never studied data structures as a course. Looks like it's about time I should really start reading CLRS which I have been procrastinating for quite a while :) Thanks again!

like image 569
Aamir Avatar asked Jul 15 '10 05:07

Aamir


2 Answers

sort arrays A and B
result will be in C
let a - the first elem of A
let b - the first elem of B
then:
1) while a < b: insert a into C and a = next elem of A
2) while a > b: b = next elem of B
3) if a = b: a = next elem of A and b = next elem of B
4) if b goes to end: insert rest of A into C and stop
5) if a goes to end: stop

like image 189
Oleg Razgulyaev Avatar answered Sep 28 '22 15:09

Oleg Razgulyaev


Iterate over each element of A, if each of those elements are not in B, then add them to a new set C.

like image 32
Brian R. Bondy Avatar answered Sep 28 '22 15:09

Brian R. Bondy