Compare all element in one array with other array

Let's say I have three mutablearrays: arr1, arr2 and arr3. I want to compare all the element in arr1 to each element in arr2, and if an element in arr2 contains all the elements in arr1, i want to add it to arr3. So i'm thinking it would look something like my code below. Is there some smart function in objective-c i don't know about, or any way this could be done?

for(int i; i < arr2.count; i++)
{
  if([arr2 objectAtIndex:i] containAllElementsInArray:arr1]])
  {
    [arr3 addObject:[arr2 objectAtIndex:i]];
  }
}

Upvotes: 3

Views: 3874

Answers (2)

C4 - Travis
C4 - Travis

Reputation: 4492

The best way to see if an array contains all the elements of another array is to work with NSSets. An NSSet will be a static set of distinct objects, which means that when you create a set from an array the set will contain only 1 entry for every disctint object in the array. In other words, an array can have multiple copies of an object, a set will have only 1 copy of each object.

The important part of using NSSet is the ability to call the isSubsetOfSet method:

isSubsetOfSet: Returns a Boolean value that indicates whether every object in the receiving set is also present in another given set.

- (BOOL)isSubsetOfSet:(NSSet *)otherSet

You will need to create a set from arr1 and compare this to each element in arr2, to see if it's a subset of that element...

NSSet *arr1set = [NSSet setWithArray:arr1];
NSSet *arr2set = [NSSet setWithArray:[arr2 objectAtIndex:i]];

if ([arr1set isSubsetOfSet:arr2set]) {
    // then the element [arr2 objectAtIndex:i] contains all the elements of arr1
    [arr3 addObject:[arr2 objectAtIndex:i]];
}

Upvotes: 8

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

Done, in 6 lines of code:

NSArray *intersectArray(NSArray *arr1, NSArray *arr2)
{
    NSMutableSet *resultSet = [NSMutableSet setWithArray:arr1];
    [resultSet intersectSet:[NSSet setWithArray:arr2]];

    return [resultSet allObjects];
}

Because NSSet can directly copy the underlying buffer of a NSArray, this should be very effective as terms of performance go.

This could also be very easily converted into a category, if you'd like.

Upvotes: 2

Related Questions