0

I'm lost in a sea of sort descriptors, dictionaries, and counted sets. Hoping someone can help me find an easier way.

Starting with a sorted array like this (of NSNumbers):

['7','7','7','5','5','5','5','5','5','3','2','2','2','2']

I want to end up with a sorted array of dictionaries that looks like this:

{'5','6'} //the number 5 appeared 6 times
{'2','4'} //the number 2 appeared 4 times
{'7','3'} //the number 7 appeared 3 times
{'3','1'} //the number 3 appeared 1 time
soleil
  • 12,133
  • 33
  • 112
  • 183
  • The dictionary you mentioned is not valid do you want `{@"Number":5, @"Repeat":6}` – Anupdas May 07 '13 at 17:55
  • It is valid. The key is the NSNumber and the value is an NSNumber of the number of times it appeared in the array. – soleil May 07 '13 at 18:00
  • I cannot edit my comment now, it's valid but its usability would be difficult if you store that way. The keys of your dictionary should be always known. With this structure you can always sort with descriptors and find a number with predicate. – Anupdas May 07 '13 at 18:09

1 Answers1

5

Here is a snippet that does what you are after, based on NSCountedSet

NSArray *numbers = @[@7,@7,@7,@5,@5,@5,@5,@5,@5,@3,@2,@2,@2,@2];

NSCountedSet *countedSet = [NSCountedSet setWithArray:numbers];

NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSNumber *num in countedSet) {
    NSUInteger c = [countedSet countForObject:num];
    [result setObject:@(c) forKey:num];
}
Monolo
  • 18,205
  • 17
  • 69
  • 103