3

Let's say I have an array (NSArray) called arrayA -> {@"A", @"B", @"C", @"D", @"E"}. And I have another array(NSArray) called arrayB -> {@"D", @"E", @"F", @"G", @"H"}.

What's the most efficient way for me to get two arrays: 1. An array that is subset of both of them, so in this case it will be {@"D", @"E"} and a subset that is unique in arrayB, so {@"F", @"G", @"H"}.

It's easier if you look at this ven diagram: http://theconsigliori.com/blog/wp-content/uploads/2009/09/venn-diagram.jpg

A and B are arrays, I want to get 2 arrays, 1. A&B 2. B-(A&B).

I am using objective-c / cocoa-touch, but any general idea is welcome. The array are going to be approximately 6000 elements long and I am doing this on an iPad.

Thanks!

dfsf
  • 63
  • 1
  • 4
  • It's not an iPad or Objective-C question, rather a CS-basics question, imho. Maybe this can help you then: http://stackoverflow.com/questions/2406097/efficient-algorithm-to-find-a-maximum-common-subset-of-two-sets – Kheldar Aug 19 '11 at 12:20

2 Answers2

10

Intersection of the two arrays:

NSMutableSet *intersectionDict = [NSMutableSet setWithArray:arrayA];
[intersectionDict intersectSet:[NSSet setWithArray:arrayB]];
NSArray *intersectionArray = [intersectionDict allObjects];

Subset of objects in arrayB that are not present in arrayA:

NSMutableArray *arrayC = [NSMutableArray arrayWithArray:arrayB];
[arrayC removeObjectsInArray:arrayA];
albertamg
  • 28,492
  • 6
  • 64
  • 71
  • @Dave DeLong Agreed. Although I'm not sure if, in this case, the ordering matters. Anyway, it is worth mentioning. – albertamg Aug 19 '11 at 14:05
  • Though, my link actually stated that already. I do find annoying when multiples of a question dilute the search for answers, this question should have been merged... – Kheldar Aug 20 '11 at 19:10
0

The method intersectSet, as stated in this post:

NSArray - check if objects are in an array? solves your problem in an Apple-efficiency way. Should be enough?

Community
  • 1
  • 1
Kheldar
  • 5,361
  • 3
  • 34
  • 63
  • 1
    Well, I'm seriously questioning why my intersectSet answer, pointing out to an already answered question, is worth negative votes, when the same answer given slightly later without the link is worth positives... WTH. – Kheldar Aug 20 '11 at 19:08