To generate all possible combinations from the letters of the given word (where each
letter is used only once) you can use the following recursive method:
- (NSArray *)allWordsFrom:(NSString *)word
{
NSMutableArray *a = [NSMutableArray array];
[self addAllWordsFrom:word withPrefix:@"" toMutableArray:a];
return a;
}
- (void)addAllWordsFrom:(NSString *)letters withPrefix:(NSString *)prefix toMutableArray:(NSMutableArray *)a
{
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// Add one letter to the prefix:
NSString *word = [prefix stringByAppendingString:substring];
[a addObject:word];
// Build combinations with remaining letters:
NSString *remainingLetters = [letters stringByReplacingCharactersInRange:substringRange withString:@""];
if ([remainingLetters length] > 0) {
[self addAllWordsFrom:remainingLetters withPrefix:word toMutableArray:a];
}
}];
}
For the word "BOX" this creates the list
B, BO, BOX, BX, BXO, O, OB, OBX, OX, OXB, X, XB, XBO, XO, XOB
and you don't have to filter the array afterwards.