Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of ahalls

ahalls's solution

to Anagram in the Objective-C Track

Published at Jul 13 2018 · 0 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
//
//  Anagram.m
//
//  Created by Andrew Halls on 11/26/13.

#import "Anagram.h"

@interface AnagramPattern : NSObject
-(instancetype) initWithString: (NSString *) string;
-(BOOL) match: (AnagramPattern *) input;
@property (nonatomic, retain) NSDictionary * dictionary;
@property (nonatomic, retain) NSString * word;
@end

@implementation AnagramPattern

-(instancetype) initWithString: (NSString *) string {
    self  = [super init];
    if (self) {
        self.word = [string lowercaseString];
    }
    return self;
}

-(NSDictionary *) dictionary {
    if (_dictionary == nil) {
        _dictionary = [self dictionaryFromWord:self.word];
    }
    return  _dictionary;
}

-(NSDictionary *) dictionaryFromWord: (NSString *) word {
    NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];

    for (NSInteger index = 0; index < word.length; index ++ ) {
        NSString * letter = [NSString stringWithFormat:@"%c", [word characterAtIndex:index]];
        
        NSInteger count = [dictionary[letter] integerValue];
        dictionary[letter] = @(count +1);
    }
    return [NSDictionary dictionaryWithDictionary:dictionary];
}

    
-(BOOL) match:(AnagramPattern *)input {
    
    if ([self.word isEqualToString:input.word]) return NO;
    
    if (self.word.length != input.word.length) return NO;
    
    NSArray * allKeys = [self.dictionary allKeys];
    
    for (NSString * letter in allKeys) {
        if ([self.dictionary[letter] integerValue] != [input.dictionary[letter] integerValue]) {
            return NO;
        }
    }
    return YES;
}

@end


@interface Anagram ()
@property (nonatomic, strong) AnagramPattern * basePattern;
@end

@implementation Anagram

-(instancetype) initWithString:(NSString *) string {
    self = [super init];
    if (self) {
        self.basePattern = [[AnagramPattern alloc] initWithString:string];
    }
    return self;
}

-(NSArray *) match: (NSArray *) array {
    NSMutableArray * result = [@[] mutableCopy];
    [array enumerateObjectsUsingBlock:^(id word, NSUInteger idx, BOOL *stop) {
        if ([self isAnagram:word]) {
            [result addObject: word];
        }
    }];
    return [NSArray arrayWithArray: result];
}

-(BOOL) isAnagram: (NSString *) word {
    return ([self.basePattern match: [[AnagramPattern alloc] initWithString: word]]);
}
    
@end

Community comments

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

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?