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

rsslldnphy's solution

to Anagram in the Objective-C Track

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

Given a word and a list of possible anagrams, select the correct sublist.

Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".

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/anagram/Anagram.m

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

Source

Inspired by the Extreme Startup game https://github.com/rchatley/extreme_startup

Submitting Incomplete Solutions

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

AnagramTest.m

#import <XCTest/XCTest.h>

#if __has_include("AnagramExample.h")
# import "AnagramExample.h"
# else
# import "Anagram.h"
#endif

NS_ASSUME_NONNULL_BEGIN


@interface AnagramTest : XCTestCase

@end

@implementation AnagramTest

- (void)testNoMatches {
    Anagram *anagram = [[Anagram alloc] initWithString:@"diaper"];
    NSArray<NSString *> *results = [anagram match:@[@"hello",@"world",@"zombies",@"pants"]];
    NSArray<NSString *> *expected = @[];
    
    XCTAssertEqualObjects(results, expected);
}

- (void)testDetectSimpleAnagram {
    Anagram *anagram = [[Anagram alloc] initWithString:@"ant"];
    NSArray<NSString *> *results = [anagram match:@[@"tan",@"stand",@"at"]];
    NSArray<NSString *> *expected = @[@"tan"];
    XCTAssertEqualObjects(results, expected);
}

- (void)testDetectMultipleAnagrams {
    Anagram *anagram = [[Anagram alloc] initWithString:@"master"];
    NSArray<NSString *> *results = [anagram match:@[@"stream",@"pigeon",@"maters"]];
    NSArray<NSString *> *expected = @[@"stream",@"maters"];
    XCTAssertEqualObjects(results, expected);
}

- (void)testDoesNotConfuseDifferentDuplicates {
    Anagram *anagram = [[Anagram alloc] initWithString:@"galea"];
    NSArray<NSString *> *results = [anagram match:@[@"eagle"]];
    NSArray<NSString *> *expected = @[];
    XCTAssertEqualObjects(results, expected);
}

- (void)testIdenticalWordIsNotAnagram {
    Anagram *anagram = [[Anagram alloc] initWithString:@"corn"];
    NSArray<NSString *> *results = [anagram match:@[@"corn", @"dark", @"Corn", @"rank", @"CORN", @"cron", @"park"]];
    NSArray<NSString *> *expected = @[@"cron"];
    XCTAssertEqualObjects(results, expected);
}

- (void)testEliminateAnagramsWithSameChecksum {
    Anagram *anagram = [[Anagram alloc] initWithString:@"mass"];
    NSArray<NSString *> *results = [anagram match:@[@"last"]];
    NSArray<NSString *> *expected = @[];
    XCTAssertEqualObjects(results, expected);
}

- (void)testEliminateAnagramSubsets {
    Anagram *anagram = [[Anagram alloc] initWithString:@"good"];
    NSArray<NSString *> *results = [anagram match:@[@"dog",@"goody"]];
    NSArray<NSString *> *expected = @[];
    XCTAssertEqualObjects(results, expected);
}

- (void)testDetectAnagram {
    Anagram *anagram = [[Anagram alloc] initWithString:@"listen"];
    NSArray<NSString *> *results = [anagram match:@[@"enlists",@"google",@"inlets",@"banana"]];
    NSArray<NSString *> *expected = @[@"inlets"];
    XCTAssertEqualObjects(results, expected);
}

- (void)testMultipleAnagrams {
    Anagram *anagram = [[Anagram alloc] initWithString:@"allergy"];
    NSArray<NSString *> *results = [anagram match:@[@"gallery",@"ballerina",@"regally",@"clergy",@"largely",@"leading"]];
    NSArray<NSString *> *expected = @[@"gallery",@"regally",@"largely"];
    XCTAssertEqualObjects(results, expected);
}

- (void)testAnagramsAreCaseInsensitive {
    Anagram *anagram = [[Anagram alloc] initWithString:@"Orchestra"];
    NSArray<NSString *> *results = [anagram match:@[@"cashregister",@"Carthorse",@"radishes"]];
    NSArray<NSString *> *expected = @[@"Carthorse"];
    XCTAssertEqualObjects(results, expected);
}

@end
NS_ASSUME_NONNULL_END
#include "Anagram.h"
#include <stdio.h>

@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;
@end

@implementation NSString (ConvertToArray)

- (NSArray *)convertToArray {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSUInteger i = 0;
    while (i < self.length) {
        NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *chStr = [self substringWithRange:range];
        [arr addObject:chStr];
        i += range.length;
    }

    return arr;
}
@end

@implementation Anagram : NSObject

- (id) initWithString: (NSString*) word_
{
    self = [ super init ];
    if (self) {
        self.word = [word_ lowercaseString];
        self.alphagram = nil;
    }
    return self;
}

- (NSString*) alphagram: (NSString*) word
{
    NSArray* chars = [[word lowercaseString] convertToArray];
    NSArray* sorted = [chars sortedArrayUsingSelector:@selector(compare:)];
    return [sorted componentsJoinedByString:@""];
}

- (NSArray*) match: (NSArray*) candidates
{
    if (self.alphagram == nil) {
        self.alphagram = [self alphagram: self.word];
    }

    NSPredicate* isAnagram = [NSPredicate predicateWithBlock: ^BOOL(id word, NSDictionary *bind){
        bool matches   = [[self alphagram:word] isEqualToString:self.alphagram];
        bool identical = [self.word isEqualToString: [word lowercaseString]];
        return matches && !identical;
    }];
    NSArray* results =  [candidates filteredArrayUsingPredicate:isAnagram];
    return results;
}

@end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of rsslldnphy

Ok, first off I have to admit to having copied and pasted the NSString category for converting a string to an array from a stackoverflow answer because I just couldn't face having to implement it myself.

I hate everything about this solution. Objective C seems to not only make you do everything for yourself (rather than providing ready-cooked methods), but also go out of its way to make it as hard for you as possible to do it.

I've given up hope of adhering to the 80 character rule.

I might have just given up hope.

Avatar of ahalls

You have mentioned the 80 character rule before. What is that ... how does that improve readability of the code ... Where specifically in this code have you violated it? I did a bit of programming in Fortran before Fortran77 and it had a line oriented syntax where lines were limited to 80 characters otherwise you had to use a continuation character to extend the line. Similar to the \ in C macros. Now there was a rule ;-)

Your complaint that there is no method in the Foundation Framework to turn a string into an array of characters I think is valid. Although its not specifically an Objective-C limitation. I think this situation comes from the fact that the Foundation Framework, all that NS stuff, is a close source commercial product of Apple computer. If it was open source we could issue a pull request and move on with our lives. Objective-C does offer categories, which you exploited here, to get around those things. I've found a few other limitations to the string library and contribute to a cocoa pod https://github.com/pwightman/RubyCocoaString ... to express my frustrations.

It's a common Objective-C idiom to use lazy initialization by redefining the generated accessor to something like this ... -(NSString *) alphagram) { if (_alphagram == nil) { _alphagram = [self alphagram: self.word]; } return _alphagram; }

Avatar of rsslldnphy

The 80 character rule is just as you describe, except not forced on you but something you do by choice. I believe it originates from the punchcards that precede programming as we know it having space for 80, er, punches per row.

The reason for sticking to it is that lines much longer than that are supposedly harder to take in all in one go - and that's a view I subscribe to. Also I do all my coding in vim with quite a large font so there's not much space on my screen for more than 80 characters anyway! In this code the only line that breaks it is line 49.

Thanks for the tip on lazy initialization, new version on its way.

Avatar of rsslldnphy

Ah, I remember why I didn't do the lazy initialization as you describe - there's already a method called alphagram, separate to the property, that I need for other purposes. Not ideal.

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?