Speedy solution for 2nd challenge


#1

Hello everybody,

here is my approach. It does check against if matching words in the “words” file are names, too (and not just listing ALL words that are in the words dictionary). And it includes a neat little trick to speed things up quite a bit. Look for yourself:

[code]int main(int argc, const char * argv[])
{

@autoreleasepool {

	NSDate *startTime = [[NSDate alloc]init];

	NSString *nameString = [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
	NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];
	
	NSArray *names = [nameString componentsSeparatedByString:@"\n"];
	NSArray *words = [wordString componentsSeparatedByString:@"\n"];

	NSUInteger numberOfWords = [words count];
	NSUInteger numberofNames = [names count];

	NSUInteger i,j=0;

	NSUInteger startAtIndex = 0;

	// We scan the word list for matching couples. We need to stop with the second last entry, otherwise the
	// compare will get out of bounds due to the (i+1).
	for (i = 0; i<(numberOfWords-1);i++) {
		
		// Is there a matching couple
		if([[words objectAtIndex:i] caseInsensitiveCompare:[words objectAtIndex:i+1]] == NSOrderedSame) {

			// A match does not necessarily mean it's a name, too. So we need to check further after finding a match
			// Note that we let the loop start from the last position (+1) where the previous match was found
			// In the first loop, we start with position 0, of course. (see below, too)
			for (j = startAtIndex;j<numberofNames;j++) {
				
				// Let's see if there is a matching name in the names list. If not, it's just a word, not a name
				if([[words objectAtIndex:i] caseInsensitiveCompare:[names objectAtIndex:j]] == NSOrderedSame) {
					NSLog(@"%@",[words objectAtIndex:i] );
					
					// This is a tiny trick. We do not have to search the words before the objectAtIndex J
					// anymore and start the next loop from the position after the last match - save around 30-40 per cent time
					startAtIndex = ++j;
					break;
				}
			}
		}
	}
}
return 0;

}[/code]

Best,

iFlash