2nd Challenge Solution


#1

Appreciate feedback on my solution to the 2nd challenge. While it appears to meet the requirements of the challenge, I cannot help but wonder if there is a more efficient way to compare the two files/arrays.

Thanks,
Jp


// Program to find names in the proper names files in the words file

#import <Foundation/Foundation.h>

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

    @autoreleasepool {
        
        // Set filename variables
        NSString *propernamesfile = @"/usr/share/dict/propernames";
        NSString *wordsfile = @"/usr/share/dict/words";
        
        // Read in propernames file
        NSString *properNamesString = [NSString stringWithContentsOfFile:propernamesfile
                                                      encoding:NSUTF8StringEncoding
                                                         error:NULL];

        // Break file contents into an array
        NSArray *properNames = [properNamesString componentsSeparatedByString:@"\n"];
        
        // Read in words file
        NSString *wordsString = [NSString stringWithContentsOfFile:wordsfile
                                                          encoding:NSUTF8StringEncoding
                                                             error:NULL];

        // Break file contents into an array
        NSArray *words = [wordsString componentsSeparatedByString:@"\n"];
        
        for (NSString *w in words) {
            NSLog(@"%@ is the word being compared",w); // Log word being compared

            for (NSString *p in properNames) {
                if ([w caseInsensitiveCompare:p] == NSOrderedSame) { // Check if w is equal to p
                    NSLog(@"%@ was found in the propernames file",w); // Tell me if you found a match
            
                }
            }
        }
    }
    return 0;
}

#2

Looks good but …

This simple code presents some interesting but tough challenges to overcome:

  • Reading a file into a string or array: What if the file is very, very, very large - say 10 giga bytes.
  • Nested for loops: What if each loop has to run millons of times.

They are easy to spot in this minuscule program.


#3

Thanks.

After posting my solution and reading through the other posts, I ended up using the faster method shared for iterating through the arrays looking for occurrences of proper names appearing in the words file. This greatly improved the overall run time and system CPU load during execution.

While I briefly wondered about the performance hit of loading the contents of both files, I had not fully thought about the implications of reading a very large file into a string/array. How would you handle a case list this?

Thanks!
J