我构建了两个版本的PHP 7函数,它接受一个数组,并返回显示原始数组成员的所有排列的数组列表。例如,对于输入[1,2,3]
,期望的输出将是1,2和3的全部六个排列。PHP:为什么这些输出不同的结果?
我期望这两个版本的函数给出相同的输出,但是不知道为什么它们没有。这是第一个(按预期工作):
function permutations(array $input): array {
$func = function (array $selected, array $chooseFrom, array &$results)
use (&$func) {
foreach ($chooseFrom as $k => $unchosen):
$selectedCopy = $selected; // make a copy
$chooseFromCopy = $chooseFrom; // make a copy
$selectedCopy[] = $unchosen; // add the next unchosen item to selected list
array_splice($chooseFromCopy, $k,1); // remove the item from chooseFrom list
$func($selectedCopy, $chooseFromCopy, $results); // recursive call
endforeach;
// If we've used all items. Add selection to results
if (empty($chooseFrom)) $results[] = $selected;
};
$results = [];
$func([], $input, $results);
return $results;
}
当我打电话permutations([1,2])
我得到预期的结果:[[1,2],[2,1]]
。
这是该函数的非工作版本。唯一的区别是在foreach
:
function permutations2(array $input): array {
$func = function (array $selected, array $chooseFrom, array &$results)
use (&$func) {
foreach ($chooseFrom as $k => $unchosen):
$chooseFromCopy = $chooseFrom; // make a copy
$selected[] = $unchosen; // add the next unchosen to the selected list
array_splice($chooseFromCopy, $k, 1); // remove the item from chooseFrom list
$func($selected, $chooseFromCopy, $results); // recursive call
endforeach;
// If we've used all items. Add selection to results
if (empty($chooseFrom)) $results[] = $selected;
};
$results = [];
$func([], $input, $results);
return $results;
}
当我打电话permutations2([1,2])
我得到一个坏的结果:[[1,2],[1,2,1]]
为什么会出现差异?
问题是关于变量“$ selected”包含第一个for循环的第一次迭代的结果,它需要在清空之前清除进入循环的下一次迭代。添加行“$ selected = array();”在endforeach语句之前将使代码工作。 –