Okay, so I'm trying to compare two strings, one eight letters long, one that could be anything from 3-8 letters long, to see if the shorter one could be made from letters in the longer one. Following some algorithms and tips I've got something which nearly works, but not in all cases.
The haystack
and needle
are fed in re-sorted into alphabetical order (for example, tomatoes
would become aemoostt
and toe
would become eot
). In some cases this works, but the issues arise if multiples of a letter exist. One such broken example is that it thinks aaabrs
does exist inside aabeirsz
, where obviously it should not since it has three A's in it.
If anyone can take a browse through my methods and spot where the issue is occurring, I'd be hugely, hugely grateful. Thanks in advance.
- (void)viewDidLoad {
[super viewDidLoad];
BOOL doesWordExist = NO;
doesWordExist = [self doesEightLetterWord: @"aabeirsz" containWord: @"aaabrs"];
NSLog(doesWordExist ? @"Does it exist? Yes" : @"Does it exist? No");
}
- (BOOL) doesEightLetterWord: (NSString* )haystack containWord: (NSString *)needle {
for (int i = 0; i < [needle length]; i++) {
NSString *currentCharacter = [needle substringWithRange:NSMakeRange(i, 1)];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: currentCharacter];
NSLog(@"Current character is %@", currentCharacter);
if ([haystack rangeOfCharacterFromSet:set].location == NSNotFound) {
NSLog(@"The letter %@ isn't found in the word %@", currentCharacter, haystack);
return NO;
} else {
NSLog(@"The letter %@ is found in the word %@", currentCharacter, haystack);
int currentLocation = [haystack rangeOfCharacterFromSet: set].location;
currentLocation++;
NSString *newHaystack = [haystack substringFromIndex: currentLocation];
NSString *newNeedle = [needle substringFromIndex: i + 1];
NSLog(@"newHaystack is %@", newHaystack);
NSLog(@"newNeedle is %@", newNeedle);
if ([newNeedle isEqualToString:@""]) {
return YES;
}
}
}
return NO;
}