Advertisement
itaiferber

Objective-C `chunk`

Sep 7th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import <Foundation/Foundation.h>
  2.  
  3. int main (int argc, char **argv)
  4. {
  5.     @autoreleasepool {
  6.         const NSUInteger iterations = 10000000;
  7.         const NSUInteger variation  = 10000000;
  8.  
  9.         NSMutableArray *original = [NSMutableArray arrayWithCapacity:iterations];
  10.         for (NSUInteger i = 0; i < iterations; i++) {
  11.             [original addObject:@(arc4random_uniform(variation))];
  12.         }
  13.        
  14.         NSMutableArray *chunked = [NSMutableArray array];
  15.         NSDate *start = [NSDate date];
  16.  
  17. #define ARRAY
  18. #ifdef ARRAY
  19.         NSArray *sorted = [original sortedArrayUsingSelector:@selector(compare:)];
  20.         NSNumber *current = nil;
  21.         for (NSNumber *number in sorted) {
  22.             if (![number isEqual:current]) {
  23.                 [chunked addObject:[NSMutableArray arrayWithObject:number]];
  24.                 current = number;
  25.             } else {
  26.                 [[chunked lastObject] addObject:number];
  27.             }
  28.         }
  29. #else
  30.         NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:original];
  31.         for (NSNumber *number in countedSet) {
  32.             NSMutableArray *chunk = [NSMutableArray array];
  33.             NSUInteger count = [set countForObject:number];
  34.             for (NSUInteger i = 0; i < count; i++) {
  35.                 [chunk addObject:number];
  36.             }
  37.            
  38.             [chunked addObject:chunk];
  39.         }
  40.  
  41.         [chunked sortUsingComparator:^(NSArray *a1, NSArray *a2) {
  42.             return [a1[0] compare:a2[0]];
  43.         }];
  44. #endif
  45.  
  46.         NSLog(@"Operation took %lf seconds.", [[NSDate date] timeIntervalSinceDate:start]);
  47.     }
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement