Κυριακή, 11 Μαρτίου 2012

The Big Nerd Ranch Guide - Challenge page 90

A nice exercise from the Big Nerd Ranch Guide

You need to write a program that finds common proper names that are also regular words. For examples "Bill" is a guy name and a "bill" needs money.
He, suggest you to use   the
/usr/share/dict/propernames
/usr/share/dict/words
two files that contain the words and names you need to check.


Here is my answer.


#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        //read in a file 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];
        //break it into an array of string
        NSArray *names = [nameString componentsSeparatedByString:@"\n"];
        NSArray *words = [wordString componentsSeparatedByString:@"\n"];
        NSMutableArray *results = [NSMutableArray array];
        NSLog(@"total names =%lu",[names count]); 
        NSLog(@"total names =%lu",[words count]); //to see the start time of searching
        //go through the array one string at a time
        for (NSString *w in words){ //235887 words
                for (NSString *n in names){ //1809 proper names
                    //only if the have the same length
                    if ((w.length == n.length)){ 
                        NSRange  re1=[w rangeOfString:n];
                        //only if they don't exactly the same go and search
                        if (re1.location == NSNotFound){
                            //look for if the w exists in names in a case -insensitive
                            NSRange  re=[w rangeOfString:n options:NSCaseInsensitiveSearch];
                            //was ti found?
                            if ((re.location != NSNotFound)){
                                NSLog(@"names=%@, words=%@",n,w);
                                [results addObject:w];
                            }
                        }
                    }
                }
        }
        
        NSLog(@"total same names=%lu",[results count]);
        
    }
    return 0;
}

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου