Permutation of factorial in php

2019-07-19 07:09发布

问题:

Don't know how to explain. But maybe example below will be make you understandable what my problem is.

Example :

I have an array with 3 elements.

$elements = array( 'A', 'B', 'C' );

The permutation will be 3 in 3. so the result are :

A-B-C ; A-C-B ; B-A-C ; B-C-A ; C-A-B; C-B-A

I don't want any permutation 2 in 3 or 1 in 3, just 3 in 3 as you can see in example. So if I have 4 elements in an array, the permutation is 4 in 4. and so on...

(I think the number of permutations is 3! = 1*2*3 = 6 permutations, 4! = 1*2*3*4 = 24 permutations... that why I call Permutations of Factorial.)

If there are other question and answer similar to my problem, please let me know

回答1:

Use a recursive function:

function permutations($elements) {
    if(count($elements)<2) return $elements;

    $newperms= array();
    foreach($elements as $key=>$element) {
        $newelements= $elements;
        unset($newelements[$key]);

        $perms= permutations($newelements);
        foreach($perms as $perm) {
            $newperms[]= $element."-".$perm;
        }
    }
    return $newperms;
}

Didn't test it, so there is still work for you ;-)



回答2:

Not sure what you need, but are you trying to produce these permutations?

This should get you started, it will perform a full permutation on any sized set you need. Added some annotations, you should be able to get the idea

$array = array('A','B','C', 'D'); 
$permutations = array($array);
$perm_pool = range(0, count($array)-1);

function getPermutation($p, $size){
    // we pass in an array of integers, basically pointers, we want to see when we've fully reversed the set
    for ($i = $size-1; $p[$i] >= $p[$i+1]; $i--){}
    // the array starts at [1,2,3,4], when we've reached [4,3,2,1], we're done.
    if ($i == -1) { return false; }

    // slide down to the next largest number, this will be our next swap
    for ($j = $size; $p[$j] <= $p[$i]; $j--) {}

    // swap it
    $tmp = $p[$i];
    $p[$i] = $p[$j];
    $p[$j] = $tmp;

    // reverse the arrangement by swapping the head and tails
    for ($i++, $j = $size; $i < $j; $i++, $j--){
        $tmp = $p[$i];
        $p[$i] = $p[$j];
        $p[$j] = $tmp;  
    }
    return $p;
}

$i=1;
while($perm_pool=getPermutation($perm_pool, count($array)-1)){
    foreach($perm_pool as $p){
        $permutations[$i][] = $array[$p];
    }
    $i++;

}