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

EggmanQi's solution

to Anagram in the Objective-C Track

Published at Apr 24 2019 · 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
//  exercismOC
//
//  Created by eggman qi on 2019/4/24.
//  Copyright © 2019 EBrainStudio. All rights reserved.
//

#import "Anagram.h"

@interface Anagram ()

@property (nonatomic, copy) NSString	*targetStr;
@property (nonatomic, strong) NSDictionary	*targetDic;

@end

@implementation Anagram

- (Anagram *)initWithString:(NSString *_Nullable)str
{
	_targetStr = str;
	_targetDic = [self strToDic:str];
	return self;
}

- (NSArray *)match:(NSArray<NSString *> *)strArr
{
	__block NSMutableArray *arr = [NSMutableArray array];
	
	[strArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
		if ([self anagram:obj]) {
			[arr addObject:obj];
		}
	}];
	
	return arr;
}

- (BOOL)anagram:(NSString *)str
{
	if (_targetStr.length != str.length) {
		return NO;
	}
	
	if ([_targetStr caseInsensitiveCompare:str] == NSOrderedSame) {
		return NO;
	}
	
	__block NSInteger matchCount = 0;
	NSDictionary *dic = [self strToDic:str];
	
	[_targetDic enumerateKeysAndObjectsUsingBlock:^(NSString *  _Nonnull key, NSNumber *  _Nonnull obj, BOOL * _Nonnull stop) {
		NSNumber *num = dic[key];
		if (num) {
			if ([num isEqualToNumber:obj]) {
				matchCount = matchCount + 1;
			}
		}
	}];
	
	return matchCount == _targetDic.count;
}

- (NSDictionary *)strToDic:(NSString *)str
{
	str = [str lowercaseString];
	NSMutableDictionary *dic = [NSMutableDictionary dictionary];
	
	for (int i=0; i<str.length; i++) {
		NSString *key = [str substringWithRange:NSMakeRange(i, 1)];
		if ([[dic allKeys] containsObject:key]) {
			NSNumber *value = dic[key];
			value = @(value.integerValue + 1);
			dic[key] = value;
		}else {
			dic[key] = @(1);
		}
	}
	
	return dic;
}

@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?