Calculate possible permutations of an array of numbers

I have an NSArray with numbers {0,1,2,3}

By calculating factorial 4 (array counter), I have 24 possible permutations of 0,1,2,3

I would like to know if there is a way to compute all these possible permutations and put them in a separate array.

For example, given the numbers above, {0,1,2,3}, the resulting permutations will be:

0123, 0132, 0213, 0231, 0312, 0321, 1023, 1032, 1203, 1230, 1302, 1320, 2013, 2031, 2103, 2130, 2301, 2310, 3012, 3021, 3102, 3120, 3201, 3210 

Any help is appreciated. Thank you very much!

+4
source share
2 answers

I was looking for the code, but I was able to figure it out :) If someone else needs it, the code looks like this:

 static NSMutableArray *results; void doPermute(NSMutableArray *input, NSMutableArray *output, NSMutableArray *used, int size, int level) { if (size == level) { NSString *word = [output componentsJoinedByString:@""]; [results addObject:word]; return; } level++; for (int i = 0; i < input.count; i++) { if ([used[i] boolValue]) { continue; } used[i] = [NSNumber numberWithBool:YES]; [output addObject:input[i]]; doPermute(input, output, used, size, level); used[i] = [NSNumber numberWithBool:NO]; [output removeLastObject]; } } NSArray *getPermutations(NSString *input, int size) { results = [[NSMutableArray alloc] init]; NSMutableArray *chars = [[NSMutableArray alloc] init]; for (int i = 0; i < [input length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%c", [input characterAtIndex:i]]; [chars addObject:ichar]; } NSMutableArray *output = [[NSMutableArray alloc] init]; NSMutableArray *used = [[NSMutableArray alloc] init]; for (int i = 0; i < chars.count; i++) { [used addObject:[NSNumber numberWithBool:NO]]; } doPermute(chars, output, used, size, 0); return results; } 

use

getPermutations (input, size)

to get an NSArray with saved permutations.

Example:

 NSLog(@"%@", getPermutations(@"0123", 4)); //console log RESULTS: ( 0123, 0132, 0213, 0231, 0312, 0321, 1023, 1032, 1203, 1230, 1302, 1320, 2013, 2031, 2103, 2130, 2301, 2310, 3012, 3021, 3102, 3120, 3201, 3210 ) 

Now it works perfect for me :)

+4
source

I would like to know if there is a way to calculate all these possible permutations

Of course (although they are not combinations , but permutations ):

 unsigned long long factorial(unsigned long long n) { return n > 1 ? n * factorial(n - 1) : 1; } unsigned long long perms = factorial(array.count); 

and put them in a separate array.

Of course, there are excellent algorithms for creating permutations (too), such as the Johnson-Trotter algorithm.

+5
source

All Articles