Skip to content

Instantly share code, notes, and snippets.

@AlexanderNorway
Created September 7, 2012 06:13
Show Gist options
  • Save AlexanderNorway/3663723 to your computer and use it in GitHub Desktop.
Save AlexanderNorway/3663723 to your computer and use it in GitHub Desktop.
Anagram Finder
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