Reputation: 1135
I've seen this question:
NSMutableArray counting occurances of objects and then re-arange the array
The solution comes very close to what i need.
The solution I'm referring to:
NSInteger countedSort(id obj1, id obj2, void *context) {
NSCountedSet *countedSet = context;
NSUInteger obj1Count = [countedSet countForObject:obj1];
NSUInteger obj2Count = [countedSet countForObject:obj2];
if (obj1Count > obj2Count) return NSOrderedAscending;
else if (obj1Count < obj2Count) return NSOrderedDescending;
return NSOrderedSame;
}
and:
NSMutableArray *array = …;
NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
autorelease];
[array sortUsingFunction:countedSort context:countedSet];
The sort returns proper sorted array by count, but i need the count either included or in another array sorted ascending.
Upvotes: 1
Views: 738
Reputation: 10065
This return a sorted array ordered by the most occurring value
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSArray *sortedValues = [countedSet.allObjects sortedArrayUsingComparator:^(id obj1, id obj2) {
NSUInteger n = [countedSet countForObject:obj1];
NSUInteger m = [countedSet countForObject:obj2];
return (n <= m)? (n < m)? NSOrderedDescending : NSOrderedSame : NSOrderedAscending;
}];
Upvotes: 0
Reputation: 21986
A solution could be to simply query the counted set for the count of any object, to build an array that keep track of the counts:
// This after having sorted the array:
NSMutableArray* counts= [NSMutableArray arrayWithCapacity: array.count];
for(id object in array) {
[counts addObject: @([countedSet countForObject: object]) ];
}
Upvotes: 1