2

Here is the original function (recursive function):

function permute($items, $perms = array()) 
{
 if (empty($items)) 
 { 
 echo join('', $perms).'<br>';
 } 
 else 
 {
 for ($i = 0; $i < count($items); ++$i) 
 {
 $newitems = $items;
 $newperms = $perms;
 $foo = implode(array_splice($newitems, $i, 1));
 array_unshift($newperms, $foo);
 permute($newitems, $newperms);
 }
 }
}
permute(array("A", 'B', 'C'));

In this case, the output will be:

cba
bca
cab
acb
bac
abc

How to modify this part:

if (empty($items)) 
{ 
 echo join('', $perms).'<br>';
} 

change it to return array of string instead of directly echo in the function?

asked Feb 25, 2015 at 6:10

1 Answer 1

3

Try this (IdeOne example):

function permute($items, $perms = array(), $result = array()) 
{
if (empty($items)) 
{ 
 $result[] = join('', $perms);
} 
else 
{
 for ($i = 0; $i < count($items); ++$i) 
 {
 $newitems = $items;
 $newperms = $perms;
 $foo = implode(array_splice($newitems, $i, 1));
 array_unshift($newperms, $foo);
 $result = permute($newitems, $newperms, $result);
 }
}
return $result;
}
$bar = permute(array("A", 'B', 'C'));
var_dump($bar);
answered Feb 25, 2015 at 6:28
1
  • This answer is missing its educational explanation. Commented May 21, 2022 at 23:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.