Permutations of Varying Size

Posted by waiwai933 on Stack Overflow See other posts from Stack Overflow or by waiwai933
Published on 2010-06-11T01:22:51Z Indexed on 2010/06/11 1:42 UTC
Read the original article Hit count: 346

I'm trying to write a function in PHP that gets all permutations of all possible sizes. I think an example would be the best way to start off:

$my_array = array(1,1,2,3);

Possible permutations of varying size:

1
1 // * See Note
2
3
1,1
1,2
1,3
// And so forth, for all the sets of size 2
1,1,2
1,1,3
1,2,1
// And so forth, for all the sets of size 3
1,1,2,3
1,1,3,2
// And so forth, for all the sets of size 4

Note: I don't care if there's a duplicate or not. For the purposes of this example, all future duplicates have been omitted.

What I have so far in PHP:

function getPermutations($my_array){

$permutation_length = 1;
$keep_going = true;    

while($keep_going){
    while($there_are_still_permutations_with_this_length){
        // Generate the next permutation and return it into an array
        // Of course, the actual important part of the code is what I'm having trouble with.
    }
    $permutation_length++;
    if($permutation_length>count($my_array)){
        $keep_going = false;
    }
    else{
        $keep_going = true;
        }
}

return $return_array;

}

The closest thing I can think of is shuffling the array, picking the first n elements, seeing if it's already in the results array, and if it's not, add it in, and then stop when there are mathematically no more possible permutations for that length. But it's ugly and resource-inefficient.

Any pseudocode algorithms would be greatly appreciated.


Also, for super-duper (worthless) bonus points, is there a way to get just 1 permutation with the function but make it so that it doesn't have to recalculate all previous permutations to get the next?

For example, I pass it a parameter 3, which means it's already done 3 permutations, and it just generates number 4 without redoing the previous 3? (Passing it the parameter is not necessary, it could keep track in a global or static).

The reason I ask this is because as the array grows, so does the number of possible combinations. Suffice it to say that one small data set with only a dozen elements grows quickly into the trillions of possible combinations and I don't want to task PHP with holding trillions of permutations in its memory at once.

© Stack Overflow or respective owner

Related posts about php

Related posts about algorithm