Skip to content

Instantly share code, notes, and snippets.

@wookay
Created March 24, 2010 03:55
Show Gist options
  • Save wookay/341973 to your computer and use it in GitHub Desktop.
Save wookay/341973 to your computer and use it in GitHub Desktop.
sortByMostFrequent
@interface NSArray (Ext)
-(NSArray*) sortByMostFrequent ;
@end
@implementation NSArray (Ext)
-(NSArray*) sortByMostFrequent {
NSMutableDictionary* frequencyDict = [NSMutableDictionary dictionary];
for (id obj in self) {
int frequency = [[frequencyDict valueForKey:obj] intValue];
[frequencyDict setValue:[NSNumber numberWithInt:frequency+1] forKey:obj];
}
NSMutableArray* ary = [NSMutableArray arrayWithCapacity:self.count];
for (id obj in self) {
[ary addObject:[NSDictionary dictionaryWithObjectsAndKeys:
obj, @"Object",
[frequencyDict valueForKey:obj], @"Frequency",
nil]];
}
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Frequency" ascending:NO];
[ary sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
return [ary valueForKey:@"Object"];
}
@end
/// example
NSArray* ary = [NSArray arrayWithObjects:@"3", @"2", @"1", @"3", @"3", @"7", nil];
NSLog(@"ary %@", [ary sortByMostFrequent]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment