typestar

word_freq.m in Objective-C

A frequency table from a split, a counting dictionary, and one sort.

// Count word frequencies in a passage and chart the leaders.
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSString *passage = @"the rain in maine falls mainly on the "
                            @"plain and the rain stays on the plain";

        // Tally every word into a mutable dictionary of counts.
        NSMutableDictionary<NSString *, NSNumber *> *counts =
            [[NSMutableDictionary alloc] init];
        for (NSString *word in
             [passage componentsSeparatedByString:@" "]) {
            NSInteger n = [counts[word] integerValue];
            counts[word] = @(n + 1);
        }

        // Rank keys by count, biggest first, ties alphabetical.
        NSArray<NSString *> *ranked = [[counts allKeys]
            sortedArrayUsingComparator:^(NSString *a, NSString *b) {
                NSComparisonResult byCount =
                    [counts[b] compare:counts[a]];
                return byCount != NSOrderedSame ? byCount
                                                : [a compare:b];
            }];

        NSLog(@"%lu distinct words", (unsigned long)[ranked count]);
        for (NSString *word in ranked) {
            NSInteger n = [counts[word] integerValue];
            NSString *bar = [@"" stringByPaddingToLength:(NSUInteger)n
                                              withString:@"#"
                                         startingAtIndex:0];
            NSLog(@"%-8s %2ld %@", [word UTF8String], (long)n, bar);
        }
    }
    return 0;
}

How it works

  1. componentsSeparatedByString: splits; boxed counts tally.
  2. The comparator ranks by count with alphabetical ties.
  3. stringByPaddingToLength: repeats # into each bar.

Keywords and builtins used here

The run, in numbers

Lines
37
Characters to type
1115
Tokens
227
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 227 seconds.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →