🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of jireton

jireton's solution

to Word Count in the Objective-C Track

Published at Jul 13 2018 · 2 comments
Instructions
Test suite
Solution

Given a phrase, count the occurrences of each word in that phrase.

For example for the input "olly olly in come free"

olly: 2
in: 1
come: 1
free: 1

Setup

There are two different methods of getting set up to run the tests with Objective-C:

  • Create an Xcode project with a test target which will run the tests.
  • Use the ruby gem objc as a test runner utility.

Both are described in more detail here: http://exercism.io/languages/objective-c

Submitting Exercises

When submitting an exercise, make sure your solution file is in the same directory as the test code.

The submit command will look something like:

exercism submit <path-to-exercism-workspace>/objective-c/word-count/WordCount.m

You can find the Exercism workspace by running exercism debug and looking for the line beginning with Workspace.

Source

This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

WordCountTest.m

#import <XCTest/XCTest.h>

#if __has_include("WordCountExample.h")
# import "WordCountExample.h"
# else
# import "WordCount.h"
#endif

NS_ASSUME_NONNULL_BEGIN

@interface WordCountTest : XCTestCase

@end

@implementation WordCountTest

- (void)testCountOneWord {
  WordCount *words = [[WordCount alloc] initWithString:@"word"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"word" : @1 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

- (void)testCountOneOfEeach {
  WordCount *words = [[WordCount alloc] initWithString:@"one of each"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"one" : @1, @"of" : @1, @"each" : @1 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

- (void)testCountMultipleOccurrences {
  WordCount *words = [[WordCount alloc] initWithString:@"one fish two fish red fish blue fish"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"one" : @1, @"fish" : @4, @"two" : @1, @"red" : @1, @"blue" : @1 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

- (void)testIgnorePunctation {
  WordCount *words = [[WordCount alloc] initWithString:@"car : carpet as java : javascript!!&@$%^&"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"car" : @1, @"carpet" : @1, @"as" : @1, @"java" : @1, @"javascript" : @1 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

- (void)testIncludeNumbers {
  WordCount *words = [[WordCount alloc] initWithString:@"testing, 1, 2 testing"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"testing" : @2, @"1" : @1, @"2" : @1 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

- (void)testNormalizeCase {
  WordCount *words = [[WordCount alloc] initWithString:@"go Go GO"];
  NSDictionary<NSString *, NSNumber *> *expected = @{ @"go" : @3 };
  NSDictionary<NSString *, NSNumber *> *result = [words count];

  XCTAssertEqualObjects(expected, result);
}

@end
NS_ASSUME_NONNULL_END
//
//  WordCount.m
//  WordCount
//
//  Created by John Ireton on 5/12/14.
//  Copyright (c) 2014 John Ireton. All rights reserved.
//

#import "WordCount.h"

@interface WordCount()
@property (nonatomic, strong) NSMutableDictionary *count;
@end


@implementation WordCount

- (instancetype)initWithString:(NSString *)sentence {
    self = [super init];
    
    _count = [[NSMutableDictionary alloc] init];
    sentence = [self stripSymbolsFromSentence:[sentence lowercaseString]];
    sentence = [self stripWhitespaceFromSentence:sentence];
    
    NSArray *words = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    for (NSString *word in words) {
        if (word) {
            int thisWordCount = (_count[word]) ? [_count[word] intValue] : 0;
            thisWordCount++;
            [_count setObject: @(thisWordCount) forKey:word];
        }
    }
    return self;
}

- (NSString *)stripSymbolsFromSentence:(NSString *)sentence {
    NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet characterSetWithCharactersInString:@" "];
    [allowedCharacters formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    NSCharacterSet *disallowedCharacters = [allowedCharacters invertedSet];
    
    return [[sentence componentsSeparatedByCharactersInSet:disallowedCharacters]
            componentsJoinedByString:@""];
}

- (NSString *)stripWhitespaceFromSentence:(NSString *)sentence {
    NSString *squashed = [sentence stringByReplacingOccurrencesOfString:@"[ ]+"
                                                             withString:@" "
                                                                options:NSRegularExpressionSearch
                                                                  range:NSMakeRange(0, sentence.length)];
    
    return [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


@end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of jireton
jireton
Solution Author
commented about 7 years ago

Resubmitting this because I discovered a bug where excessive whitespace was causing an extra dictionary entry for "". Suggest that unit tests should be comparing object count of the result dictionary vs expected, especially for -testIgnorePunctation test.

Avatar of dynamite8

Here, count was expected to be a method rather than a property name. You can tell from the test call. Also, moving the functionality from init method to the count method would have made it more reusable.

componentsSeparatedByString can also be used to slit the sentence into words.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?