Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining NSArrays Through Intersection and Union

I have two NSArrays A and B that share some common elements, e.g.

A: 1,2,3,4,5 
B: 4,5,6,7

I would like to create a new NSArray consisting of the contents common between the two NSArrays joined with the contents of the second NSArray while maintaining the order of the elements and removing duplicates. That is, I would like (A ∩ B) ∪ B.

The operation on the previous NSArrays would yield:

A ∩ B: 4,5
(A ∩ B) ∪ B: 4,5,6,7

How do I accomplish this in Objective-C?

like image 528
Mat Kelly Avatar asked Sep 30 '11 21:09

Mat Kelly


1 Answers

Convert the NSArrays to NSSets, the standard set operations are available.

NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
NSArray *b = [NSArray arrayWithObjects:@"4", @"5", @"6", @"7", nil];

NSMutableSet *setA = [NSMutableSet setWithArray:a];
NSSet *setB = [NSSet setWithArray:b];
[setA intersectSet:setB];
NSLog(@"c: %@", [setA allObjects]);

NSLog output: c: (4, 5)

[setA unionSet:setB];
NSLog(@"d: %@", [setA allObjects]);

NSLog output: d: (6, 4, 7, 5)

like image 127
zaph Avatar answered Sep 27 '22 19:09

zaph