Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Last active August 29, 2015 13:57
Show Gist options
  • Save isoiphone/9406773 to your computer and use it in GitHub Desktop.
Save isoiphone/9406773 to your computer and use it in GitHub Desktop.
Given an array, remove the duplicates and return a unique array keeping the first occurrence of the duplicates and the order. [@2, @1, @3, @1, @2] --> [@2, @1, @3]
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface Test : NSObject
@end
@implementation Test
+ (NSArray*)arrayWithoutDuplicates:(NSArray*)a {
NSMutableSet* s = [NSMutableSet set];
NSMutableArray* result = [NSMutableArray array];
for (id obj in a) {
if (![s containsObject:obj]) {
[s addObject:obj];
[result addObject:obj];
}
}
return result;
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSArray* a = @[@2,@1,@3,@1,@2];
NSArray* b = @[@2,@1,@3];
NSLog(@"%@", [Test arrayWithoutDuplicates:a]);
NSLog(@"%d", [[Test arrayWithoutDuplicates:a] isEqualTo:b]);
}
}
// OUTPUT:
// running 32 lines of Objective-C
// 2014-03-07 07:10:29.856 solution[21] (2, 1, 3)
// 2014-03-07 07:10:29.862 solution[21] 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment