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
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
-
This answer is missing its educational explanation.2022年05月21日 23:32:32 +00:00Commented May 21, 2022 at 23:32
lang-php