【发布时间】:2017-02-19 19:00:04
【问题描述】:
我有一个数组
$a = array(1,2,3,4,5);
我想获取数组中$n 元素的所有组合
$n = 3
输出
1 2 3
1 3 4
1 4 5
2 3 5
2 4 5
.
.
.
5 1 2
【问题讨论】:
标签: php arrays permutation
我有一个数组
$a = array(1,2,3,4,5);
我想获取数组中$n 元素的所有组合
$n = 3
输出
1 2 3
1 3 4
1 4 5
2 3 5
2 4 5
.
.
.
5 1 2
【问题讨论】:
标签: php arrays permutation
您基本上会在数组中从头到尾将当前数字放在开头,然后将数组的所有排列都附加到数组的开头,而不是开头的数字。如果你使用递归,那相当简单。 示例:
input: [1] [2] [3]
step 1: [1] [unknown] [unknown]
现在调用用于生成所有排列的函数(此函数)并将您获得的所有数组附加到该函数中。
每个函数调用所需的迭代次数为n!(n)*(n-1)*(n-2) ...。
【讨论】:
不久前,我在日常工作(不是程序员)中遇到了类似的问题。我找到了以下代码的 javascript 版本。希望我已经对它进行了足够好的转码。我的评论。如果你能等一会(马上要去度假),那么我可以研究如何限制递归调用以减少资源占用。
<?php
function combinations($arr){
$result = array();
//the result array, returned by this outer function.
function fn($active, $rest, &$a){
if(!$active && !$rest)
return;//If we have empty arrays, stoppit
if(!$rest){
//Are we out of remaining options? Yep, add the active array.
$a[] = $active;
}else{
/*
we are currently splitting the work between the two options. First is that we compute the
combinations of the currently $active and the $rest array offset by 1.
*/
fn($active, array_slice($rest,1), $a);
$active[] = $rest[0];
//Next we add in the first element of the rest array to the active array, and slice off that new element to avoid duplicates.
fn($active, array_slice($rest,1), $a);
}
} //Function that actually does the work;
fn([],$arr,$result);
return $result;
}
$combos = combinations([1,2,3,4,5]);
$combos = array_filter($combos,function($item){
return count($item) == 2;
});
print_r($combos);
?>
【讨论】: