Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Intersection of NSMutableArrays

I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"]; NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"]; NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"]; 

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@"Jack",@"Lisa"]; 

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

like image 917
aeciftci Avatar asked May 16 '11 21:05

aeciftci


People also ask

How do you find the intersection of two arrays?

Solution steps We define an output list intersection[] to store the common elements. Now we sort array Y[] in increasing order. We can use O(nlogn) sorting algorithms like heap sort or quick sort or merge sort. We run a loop from i = 0 to m - 1 and search each element X[i] in the sorted array Y[] using binary search.

How do you find the intersection in Java?

An intersection is a group of common items that belong to two different sets. To get the intersection of two arrays, follow these steps: Push first array in a HashSet instance. Use retainAll() method to retain only elements which are present in second array.


2 Answers

Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1]; [intersection intersectSet:[NSSet setWithArray:array2]]; [intersection intersectSet:[NSSet setWithArray:array3]];  NSArray *array4 = [intersection allObjects]; 

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.


As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.

like image 187
Dave DeLong Avatar answered Sep 21 '22 14:09

Dave DeLong


Have a look at this post.

In short: if you can use NSSet instead of NSArray, then it's trivial (NSMutableSet has intersectSet:).

Otherwise, you can build an NSSet from your NSArray and go back to the above case.

like image 33
sergio Avatar answered Sep 18 '22 14:09

sergio