Расширенный ответ SSJ на
-лог распечаток для ясности
- работа с любым объектом
- больше объяснений
-обнаружить крайние случаи, когда может возникнуть ошибка
[self allPermutationsOfArray:@[@1,@2,@3,@4]]; // usage
...
-(void)allPermutationsOfArray:(NSArray*)array
{
NSMutableArray *permutations = [NSMutableArray new];
for (int i = 0; i < array.count; i++) { // for each item in the array
NSLog(@"iteration %d", i);
if (permutations.count == 0) { // first time only
NSLog(@"creating initial list");
for (id item in array) { // create a 2d array starting with each of the individual items
NSMutableArray* partialList = [NSMutableArray arrayWithObject:item];
[permutations addObject:partialList]; // where array = [1,2,3] permutations = [ [1] [2] [3] ] as a starting point for all options
}
} else { // second and remainder of the loops
NSMutableArray *permutationsCopy = [permutations mutableCopy]; // copy the original array of permutations
[permutations removeAllObjects]; // remove all from original array
for (id item in array) { // for each item in the original list
NSLog(@"adding item %@ where it doesnt exist", item);
for (NSMutableArray *partialList in permutationsCopy) { // loop through the arrays in the copy
if ([partialList containsObject:item] == false) { // add an item to the partial list if its not already
// update a copy of the array
NSMutableArray *newArray = [NSMutableArray arrayWithArray:partialList];
[newArray addObject:item];
// add to the final list of permutations
[permutations addObject:newArray];
}
}
}
}
[self printArrayInLine:permutations];
}
NSLog(@"%lu permutations",(unsigned long)permutations.count);
}
-(void)printArrayInLine:(NSArray*)twoDimensionArray
{
NSString* line = @"\n";
for (NSArray* array in twoDimensionArray) {
line = [line stringByAppendingString:@"["];
for (id item in array) {
line = [line stringByAppendingString:[NSString stringWithFormat:@"%@,",item]];
}
line = [line stringByAppendingString:@"]\n"];
}
NSLog(@"%@", line);
}
вывод журнала для ввода @ [@ 1, @ 2, @ 3]
iteration 0
creating initial list
[1,]
[2,]
[3,]
iteration 1
adding item 1 where it doesnt exist and creates a new list
adding item 2 where it doesnt exist and creates a new list
adding item 3 where it doesnt exist and creates a new list
[2,1,]
[3,1,]
[1,2,]
[3,2,]
[1,3,]
[2,3,]
iteration 2
adding item 1 where it doesnt exist and creates a new list
adding item 2 where it doesnt exist and creates a new list
adding item 3 where it doesnt exist and creates a new list
[3,2,1,]
[2,3,1,]
[3,1,2,]
[1,3,2,]
[2,1,3,]
[1,2,3,]
6 permutations