Created
September 7, 2012 06:13
-
-
Save AlexanderNorway/3663723 to your computer and use it in GitHub Desktop.
Anagram Finder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"eventyr" ofType:@"txt"]; | |
if (filePath) { | |
NSData *fileData = [NSData dataWithContentsOfFile:filePath]; | |
NSString* words = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding]; | |
NSMutableArray *lines = [[words componentsSeparatedByString:@"\n"] mutableCopy]; | |
NSMutableArray *possibleMatches = [[NSMutableArray alloc]init]; | |
NSMutableArray *matches = [[NSMutableArray alloc]init]; | |
for (int i=0; i<lines.count; i++) { | |
NSString *currentString = [lines objectAtIndex:i]; | |
NSNumber *currentStringLength = [NSNumber numberWithInt:(int)currentString.length]; | |
for (int j=0; j<lines.count; j++) { | |
NSString *compareString = [lines objectAtIndex:j]; | |
NSNumber *compareStringLength = [NSNumber numberWithInt:(int)compareString.length]; | |
if (![currentString isEqualToString:compareString]) { | |
if ([currentStringLength compare:compareStringLength] == NSOrderedSame) { | |
[possibleMatches addObject:compareString]; | |
} | |
} | |
} | |
NSMutableArray *currentCharArray = [[NSMutableArray alloc]init]; | |
NSMutableArray *compareCharArray = [[NSMutableArray alloc]init]; | |
for (int k = 0; k<possibleMatches.count; k++) { | |
for (int l = 0; l<[currentStringLength intValue]; l++) { | |
[currentCharArray addObject:[[currentString lowercaseString] substringWithRange: NSMakeRange (l, 1)]]; | |
[compareCharArray addObject:[[[possibleMatches objectAtIndex:k] lowercaseString] substringWithRange: NSMakeRange (l, 1)]]; | |
} | |
[currentCharArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; | |
[compareCharArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; | |
if ([compareCharArray isEqualToArray:currentCharArray]) { | |
[matches addObject:[possibleMatches objectAtIndex:k]]; | |
} | |
[currentCharArray removeAllObjects]; | |
[compareCharArray removeAllObjects]; | |
} | |
if (matches.count > 0) { | |
[matches insertObject:currentString atIndex:0]; | |
NSString *result = [[matches valueForKey:@"description"] componentsJoinedByString:@" "]; | |
NSLog(@"Result: %@", result); | |
} | |
[matches removeAllObjects]; | |
[possibleMatches removeAllObjects]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment