// Usage: WordCount file // Counts the frequency of case insensitive words in the given input file and prints them // in descending order of frequency, sorted ascending alphabetically as a second key // // David Hutchens // March 20, 2007 #import @interface CountedWord : NSObject { NSString *str; int cnt; } - (id)initWithString:(NSString *)str; - (NSString *)string; - (void)incrementCount; - (int)count; - (int)compare:(CountedWord *)other; @end @implementation CountedWord - (id)initWithString:(NSString *)theStr { [super init]; str = theStr; cnt = 0; return self; } - (NSString *)string { return str; } - (void)incrementCount { cnt++; } - (int)count { return cnt; } - (int)compare:(CountedWord *)other { int oc = [other count]; if (cnt > oc) { return NSOrderedAscending; } else if (cnt < oc) { return NSOrderedDescending; } else { return [str compare:[other string]]; } } @end void printArray (NSArray *countedWordArray) { int i, c = [countedWordArray count]; for (i=0; i < c; i++) { CountedWord *cw = [countedWordArray objectAtIndex:i]; printf("%i\t%s\n", [cw count], [[cw string] cString]); } } NSArray *sortedArrayFromString(NSString *str) { NSArray *theWords = [[str lowercaseString] componentsSeparatedByString:@" "]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; int i, c = [theWords count]; for (i=0; i < c; i++) { NSString *word = [theWords objectAtIndex:i]; if ( ! [word isEqualToString:@""]) { CountedWord *cw = [dict objectForKey:word]; if (cw == nil) { cw = [[CountedWord alloc] initWithString:word]; [dict setObject:cw forKey:word]; } [cw incrementCount]; } } return [[dict allValues] sortedArrayUsingSelector:@selector(compare:)]; } int main (int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSError *theError = nil; NSMutableString *input = [NSMutableString stringWithContentsOfFile:[NSString stringWithCString:argv[1]] encoding:NSNEXTSTEPStringEncoding error:&theError]; [input replaceOccurrencesOfString:@"\t" withString:@" " options:NSLiteralSearch range:NSMakeRange(0,[input length])]; [input replaceOccurrencesOfString:@"\r" withString:@" " options:NSLiteralSearch range:NSMakeRange(0,[input length])]; [input replaceOccurrencesOfString:@"\n" withString:@" " options:NSLiteralSearch range:NSMakeRange(0,[input length])]; printArray(sortedArrayFromString(input)); [pool release]; return 0; }