Search code examples
phppermutationheaps-algorithm

Heap alogrithm implementation in PHP produces wrong results


Below is a PHP function based on Heap algorithm for finding permutations. The function works fine in JavaScript but fails in PHP. Why ?

function generate($n,$A) {
    if ($n === 1) {
        var_dump($A); 
        return $A;
    } else { 
        for ($i = 0; $i < $n - 1; $i++) {
            generate($n - 1, $A); 
            if ($n % 2 === 0) {
                $t = $A[$i];
                $A[$i] = $A[$n - 1];
                $A[$n - 1] = $t;
            }else { 
                $t = $A[0];
                $A[0] = $A[$n - 1];
                $A[$n - 1] = $t; 
            }
        }
        generate($n - 1, $A);
    }
}

generate(3,array('a','b','c')); 

Output of the function should be as follows:

[ "a", "b", "c" ],
[ "b", "a", "c" ],
[ "c", "a", "b" ],
[ "a", "c", "b" ],
[ "b", "c", "a" ],
[ "c", "b", "a" ],

but I get:

[ "a", "b", "c" ],
[ "b", "a", "c" ],
[ "c", "b", "a" ],
[ "b", "c", "a" ],
[ "a", "b", "c" ],
[ "b", "a" ,"c" ] 

Solution

  • Here you go:

    function swap(&$x, &$y) {
        list($x, $y) = array($y, $x);
    }
    
    function generate($n, &$A) {
        if($n === 1) {
            echo "<pre>";
            print_r($A);
            echo "</pre>";
            return $A;
    
        } else {
    
            for($i = 0; $i < $n - 1; $i++) {
                generate($n - 1, $A);
                if(($n % 2) === 0) {
                    swap($A[$i], $A[$n - 1]);
    
                } else {
                    swap($A[$n - 1], $A[0]);
                }
            }
            generate($n - 1, $A);
        }
    }
    
    $A = array('a','b','c');
    generate(3, $A);