Advertisement
Guest User

Untitled

a guest
Oct 30th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. BOOL isAnagram(NSString* word1, NSString* word2) {
  2.     NSString* strippedWord1 = [word1 stringByReplacingOccurrencesOfString:@" " withString:@""];
  3.     NSString* strippedWord2 = [word2 stringByReplacingOccurrencesOfString:@" " withString:@""];
  4.    
  5.     if (strippedWord1.length != strippedWord2.length) {
  6.         return NO;
  7.     }
  8.    
  9.     NSCountedSet *word1Set = [NSCountedSet new];
  10.     NSCountedSet *word2Set = [NSCountedSet new];
  11.  
  12.     int i = 0;
  13.     for (i = 0; i < strippedWord1.length; i++)
  14.     {
  15.         [word1Set addObject:[NSString stringWithFormat:@"%C", [strippedWord1 characterAtIndex:i]]];
  16.         [word2Set addObject:[NSString stringWithFormat:@"%C", [strippedWord2 characterAtIndex:i]]];
  17.     }
  18.  
  19.     return [word1Set isEqual:word2Set];
  20. }
  21.  
  22. NSArray* anagramize(NSArray* input) {
  23.     NSMutableSet* addedIndices = [NSMutableSet new];
  24.     NSMutableArray* output = [NSMutableArray array];
  25.        
  26.     int i, j;
  27.     for (i = 0; i < [input count]; ++i) {
  28.         if ([addedIndices member: [NSNumber numberWithInt: i]] != nil) {
  29.             continue;
  30.         }
  31.         NSMutableArray* resultStringArray = [NSMutableArray array];
  32.         [resultStringArray addObject: [input objectAtIndex: i]];
  33.        
  34.         for (j = i + 1; j < [input count]; ++j) {
  35.             if ([addedIndices member: [NSNumber numberWithInt: j]] != nil) {
  36.                 continue;
  37.             }
  38.            
  39.             if (isAnagram([input objectAtIndex: i], [input objectAtIndex: j])) {
  40.                 [resultStringArray addObject: [input objectAtIndex: j]];
  41.                
  42.                 [addedIndices addObject: [NSNumber numberWithInt: j]];
  43.             }
  44.         }
  45.        
  46.         resultStringArray = [resultStringArray sortedArrayUsingSelector:@selector(compare:)];
  47.         NSString * resultString = [[resultStringArray valueForKey:@"description"] componentsJoinedByString:@","];
  48.        
  49.         [output addObject: resultString];        
  50.     }
  51.    
  52.     output = [output sortedArrayUsingSelector:@selector(compare:)];
  53.  
  54.     return output;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement