修复排列输出
嘿,我已经为类创建了一个递归排列函数,但我的输出不太令人满意。 http://codepad.org/DOaMP9oc
function permute($arr) {
$out = array();
if (count($arr) > 1) {
$i = 0;
foreach($arr as $r => $c) {
$n = $arr;
unset($n[$r]);
$out[$c] = permute($n);
}
}
else
return array_shift($arr);
return $out;
}
如果输入是 array(1, 2,3,4,5)
,输出为:
Array
(
[1] => Array
(
[2] => Array
(
[3] => Array
(
[4] => 5
[5] => 4
)
[4] => Array
(
[3] => 5
[5] => 3
)
[5] => Array
(
[3] => 4
[4] => 3
)
)
ETC......................
This is all Correct,你可以像这个键一样读取它.key.key.key.value 或12345
,12354
,12435
目前,为了将此输出转换为可读的内容,我正在使用这个丑陋的代码块: http://codepad.org/qyWcRBCl
foreach($out as $k => $a)
foreach($a as $l => $b)
foreach ($b as $m => $c)
foreach ($c as $n => $d)
echo $k.$l.$m.$n.$d.'<br>';
如何更改我的函数以消除 foreach
以与 permute()
类似的格式进行堆栈和输出。
Hey there I've made a recursive permutation function for class, but I output is less than favorable.
http://codepad.org/DOaMP9oc
function permute($arr) {
$out = array();
if (count($arr) > 1) {
$i = 0;
foreach($arr as $r => $c) {
$n = $arr;
unset($n[$r]);
$out[$c] = permute($n);
}
}
else
return array_shift($arr);
return $out;
}
If input is array(1,2,3,4,5)
, Output is:
Array
(
[1] => Array
(
[2] => Array
(
[3] => Array
(
[4] => 5
[5] => 4
)
[4] => Array
(
[3] => 5
[5] => 3
)
[5] => Array
(
[3] => 4
[4] => 3
)
)
ETC......................
This is all Correct, you can read it like this key.key.key.key.value or 12345
,12354
,12435
Currently, to convert this output to something readable, I'm using this ugly block of code:
http://codepad.org/qyWcRBCl
foreach($out as $k => $a)
foreach($a as $l => $b)
foreach ($b as $m => $c)
foreach ($c as $n => $d)
echo $k.$l.$m.$n.$d.'<br>';
How can I alter my function to eliminate the foreach
stack and output in a similar format from permute()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的解决方案是处理字符串:
您已经有了一个有效的实现,所以我毫不犹豫地将其提供给您。请注意,数组不是按顺序创建的,因此我只是在最后对其进行排序。另请注意,这仅适用于您打算具有 1 个字符值的内容,因此对汽车名称进行排列是行不通的。
即使您不喜欢这个答案,我建议您对数组使用类型提示:
这将强制您向其中传递一个数组。
My solution is to work on strings:
You already have a working implementation so I have no qualms in giving that to you. Note that the array is not created in order, so I simply sort it at the end. Also note that this only works on things that you intend to have the value of 1 character, so doing a permutation of car names would not work.
Even if you don't like this answer, I suggest that you use a type-hint for array:
This will enforce that you pass an array into it.
这是我的排列函数,我们可以以简单的方式显示结果
Here is my permutation function and we can display results in simple way
我选择使用以下函数:
但是,我仍然想在单个递归函数中执行此操作。
I opted to use the following function:
However, I'd still like to do this in a singular recursive function.