My solution for challenge 2


#1

Here’s my solution for challenge 2.

My view on this was that all the names are capitalised, so convert the big long name string to all lower case, then perform a case sensitive (which I think is the default?) search.
Anyway, heres my code:

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

    @autoreleasepool {
        
//      Read in lines as a huge string (ignoring the possibility of an error
        NSString *nameString = [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames"
                                                         encoding:NSUTF8StringEncoding
                                                            error:NULL];
        NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
                                                         encoding:NSUTF8StringEncoding
                                                            error:NULL];

//      Convert to lower case string
        NSString *nameStringLC = [nameString lowercaseString];
        
//      Break it into an array of strings
        NSArray *lowercaseNames = [nameStringLC componentsSeparatedByString:@"\n"];
        
//      Go through the array one string at a time
        NSUInteger wordCount = 0;
        for (NSString *i in lowercaseNames) {
            NSRange r = [wordString rangeOfString:i];
            
//      Was it found?
            if (r.location != NSNotFound) {
//                NSLog(@"%@", i);
                wordCount++;
            }
        }

//      Print the value of wordCount which should be the number of names listed in lowercase in the Words file
        NSLog(@"%lu", (long)wordCount);
        
    }
    return 0;
}

Total ended up being 692… Does this match anyone elses result?


#2

Hmm, I looked through other answers on the forum, and see that other people got 293/294 as a result.
Checking the first word/name, it showed Adam being a word (which isnt the case according to the words file), so I’ve had to revisit this…


#3

Hi Sepuku,

You are on the right track, but the problem with your code is that the method rangeOfString will match a substring of the whole string, meaning you will get undesirable matches. for example, If the string that you are searching for using rangeOfString is adam, you will also match all of the following:

Adam
adamant
adamantean
adamantine
adamantinoma
adamantoblast
adamantoblastoma
adamantoid
adamantoma
adamas
Adamastor
adambulacral
adamellite
Adamhood
Adamic
Adamical
Adamically
adamine
Adamite
adamite
Adamitic
Adamitical
Adamitism
Adamsia
adamsite

since they all start with adam. You have to find a diferent method to use that will give you an exact match. My total match count at the end was 294.