Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BOOL isAnagram(NSString* word1, NSString* word2) {
- NSString* strippedWord1 = [word1 stringByReplacingOccurrencesOfString:@" " withString:@""];
- NSString* strippedWord2 = [word2 stringByReplacingOccurrencesOfString:@" " withString:@""];
- if (strippedWord1.length != strippedWord2.length) {
- return NO;
- }
- NSCountedSet *word1Set = [NSCountedSet new];
- NSCountedSet *word2Set = [NSCountedSet new];
- int i = 0;
- for (i = 0; i < strippedWord1.length; i++)
- {
- [word1Set addObject:[NSString stringWithFormat:@"%C", [strippedWord1 characterAtIndex:i]]];
- [word2Set addObject:[NSString stringWithFormat:@"%C", [strippedWord2 characterAtIndex:i]]];
- }
- return [word1Set isEqual:word2Set];
- }
- NSArray* anagramize(NSArray* input) {
- NSMutableSet* addedIndices = [NSMutableSet new];
- NSMutableArray* output = [NSMutableArray array];
- int i, j;
- for (i = 0; i < [input count]; ++i) {
- if ([addedIndices member: [NSNumber numberWithInt: i]] != nil) {
- continue;
- }
- NSMutableArray* resultStringArray = [NSMutableArray array];
- [resultStringArray addObject: [input objectAtIndex: i]];
- for (j = i + 1; j < [input count]; ++j) {
- if ([addedIndices member: [NSNumber numberWithInt: j]] != nil) {
- continue;
- }
- if (isAnagram([input objectAtIndex: i], [input objectAtIndex: j])) {
- [resultStringArray addObject: [input objectAtIndex: j]];
- [addedIndices addObject: [NSNumber numberWithInt: j]];
- }
- }
- resultStringArray = [resultStringArray sortedArrayUsingSelector:@selector(compare:)];
- NSString * resultString = [[resultStringArray valueForKey:@"description"] componentsJoinedByString:@","];
- [output addObject: resultString];
- }
- output = [output sortedArrayUsingSelector:@selector(compare:)];
- return output;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement