I’m working my way through the book and think I have a solution to Challenge #2 for this chapter but I was wondering what the correct number of matches we should find is. I got 1,602 matches (although I believe that includes at least one blank entry). Is that right?
Here’s my code:
[code]int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *nameString
= [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *names = [nameString componentsSeparatedByString:@"\n"];
NSString *wordString
= [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *words = [wordString componentsSeparatedByString:@"\n"];
long matches = 0;
for (NSString *w in words) {
for (NSString *n in names) {
if ([n caseInsensitiveCompare:w] == NSOrderedSame) {
NSLog(@"%@ and %@ are the same", n, w);
matches++;
}
}
}
NSLog(@"There were %lu matches.", matches);
}
return 0;
Whoops! Should’ve persisted a little longer before posting…
My output showed that the strings in “words” included proper names as well as words. I added a blank if statement before my caseInsensitive check such that if a word from words is exactly the same as a name from names, it’ll pass on by and not count as a match. My number of matches fell dramatically - now I get 293. That seems more accurate, but I’m still curious…am I right?
[code]int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *nameString
= [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *names = [nameString componentsSeparatedByString:@"\n"];
NSString *wordString
= [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *words = [wordString componentsSeparatedByString:@"\n"];
long matches = 0;
for (NSString *w in words) {
for (NSString *n in names) {
if ([n isEqualToString:w]) {
}
else if ([n caseInsensitiveCompare:w] == NSOrderedSame) {
NSLog(@"%@ and %@ are the same", n, w);
matches++;
}
}
}
NSLog(@"There were %lu matches.", matches);
}
return 0;
I got the same count, by slightly different means. Confusingly the proper names list contains names such as ‘Plastic’, and the web2 word list contains lowercase ‘alison’ and ‘elaine’, which had me thinking I was on the wrong track for a while, but I’m pretty certain this was what was intended… Likewise would appreciate any constructive criticism of my solution.
// loop through proper names
for (NSString *name in names) {
//convert proper names to all lowercase
NSString *lcn = [name lowercaseString];
//check lwrcase names against word array
for (NSString *w in words) {
//if lwrcase name matches word, assume name is also noun (alison?)
if ([lcn isEqualToString:w]) {
// click counter
count++;
// print counter and matching name/noun
NSLog(@"%lu: %@",count,w);
// next name to check
}
}
}
}