Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicates in NSArray

Say you have an NSArray with duplicates @[1,2,3,1,1,2,4,5,6];

Find all the duplicates; this can be in pseudocode. This is more of a algorithm question than a Foundation framework (without the use of NSSet) question.

like image 581
iCanObjSeeSharp Avatar asked Jul 17 '13 04:07

iCanObjSeeSharp


2 Answers

as @Lithu described, use NSCountedSet , see the below code.

NSArray *arr = [[NSArray alloc]initWithObjects:@(1),@(1),@(2), @(1),nil];
NSCountedSet *cs = [[NSCountedSet alloc] initWithArray:arr];
NSLog(@"object count greater than 1 are");
for(NSNumber *num in cs)
{
    if([cs countForObject:num]>1)
    NSLog(@"%@",num);
}
like image 50
Manish Agrawal Avatar answered Sep 28 '22 05:09

Manish Agrawal


Use an NSCountedSet and only print the elements that returns a number>1 for countForObject: method

Refer this for more information

like image 27
Lithu T.V Avatar answered Sep 28 '22 05:09

Lithu T.V