Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate possible permutations of an array of numbers

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

Calculating the factorial of 4 (the count of the array), I have 24 possible permutations of 0,1,2,3

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

For example, given the numbers above, {0,1,2,3}, the resulting permutations would 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 greatly appreciated. Thank you so much!

like image 330
jacob Avatar asked Apr 01 '13 06:04

jacob


1 Answers

I was looking for code, but I managed to figure it out :) If anyone else needs it, the code is as follows:

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 the permutations stored.

For 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
)

It's working perfect for me now :)

like image 81
jacob Avatar answered Sep 22 '22 18:09

jacob