2013-04-01 53 views
4

我有一個NSArray與數字{0,1,2,3}計算數字的陣列的可能的排列

計算的4(陣列的計數)的階乘,我有24個可能的排列0,1,2,3

我想知道是否有辦法計算所有這些可能的排列並將它們放置在單獨的數組中。

例如,給定上述數字,{0,1,2,3},將得到的置換將是:

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

任何幫助不勝感激。非常感謝!

回答

4

我一直在尋找的代碼,但我設法弄清楚:)如果任何人都需要它,代碼如下:

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; 
} 

使用

getPermutations(輸入,大小)

得到一個NSArray與存儲的排列。

例如:

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, 

) 

它現在的工作非常適合我:)

5

我想知道是否有計算所有這些可能的排列

肯定的一種方式(儘管他們不是combinations而是permutations):

unsigned long long factorial(unsigned long long n) 
{ 
    return n > 1 ? n * factorial(n - 1) : 1; 
} 

unsigned long long perms = factorial(array.count); 

並將它們放置在單獨的陣列中。

當然,有很好的排列算法(例如Johnson-Trotter algorithm)。