0

cannot return function value, if i print inside the function the value had printed when i make return variable that that it will be return zero my code following

    function permute($str,$i,$n) {
$b="";
   if ($i == $n)
        $b .=$str.",";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }

   }

   return $b;


}
function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   
$str = "375";
$test=permute($str,0,strlen($str));
echo $test;
4
  • @Nouphal.M, Put that as an answer mate. Commented Feb 21, 2014 at 6:57
  • yes i need array with possible permutations Commented Feb 21, 2014 at 7:02
  • Nouphal.M : thanks dude i got it Commented Feb 21, 2014 at 7:04
  • Sorry @Sankar i went for friday namaz Commented Feb 21, 2014 at 9:41

3 Answers 3

2
  function permute($str,$i,$n) {
   ....
          $b . = permute($str, $i+1, $n);
   ....

   return $b;


}

You are not using the result of inner call.

Sign up to request clarification or add additional context in comments.

2 Comments

ya sorry. he is not returning any thing from swap
its ok ya i got that]
0

You have to use the return value in the loop

<?php
function permute($str,$i,$n){
    $b=NULL;
    if ($i == $n){
        $b= $str.",";
     }else {
        for ($j = $i; $j < $n; $j++){
        swap($str,$i,$j);
        $b.=permute($str, $i+1, $n); //ERROR HERE
        swap($str,$i,$j); // backtrack.
        }
    }
    return $b;
}

Comments

0

This doesn't tell you exactly why your function was wrong, but this is how you would generate an array of possible permutations:

// permute prefix $s with set $r and store results in $a
function permute($r, array &$a, $s = '')
{
    if (!strlen($r)) {
        $a[] = $s; // store result
        return;
    }

    for ($i = 0; $i < strlen($r); ++$i) {
        // recurse
        permute(substr_replace($tmp = $r, '', $i, 1), $a, $s . $r[$i]);
    }
}

$str = "375"; 
$res = [];

permute($str, $res);

print_r($res);

1 Comment

Thanks dude but i got the result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.