使用阶乘原理通过阶乘获取一个一维数组中全部的组合情况
代码如下
<?php
namespace App\Handlers;
class FactorialHandler
{
public function getArrAllCombineByFactor(array $arr) : array
{
if (count($arr) > 1) {
$combineArr = [];
foreach ($arr as $k => $v) {
$temArr = $this->arrRmoveValueByKey($arr, $k);
$sonCombineArr = $this->getArrAllCombineByFactor($temArr);
foreach ($sonCombineArr as $value) {
$combineArr[] = $v . '|' . $value;
}
}
return $combineArr;
} else {
return $arr;
}
}
public function arrRmoveValueByKey(array $arr, $k) : array
{
unset($arr[$k]);
$arr = array_values($arr);
return $arr;
}
}
使用
$arr = ['1_1', '2_3', '4_6'];
$factorialInstance = new FactorialHandler();
$result = $factorialInstance->getArrAllCombineByFactor($arr);
var_dump($result);
返回结果
array:6 [
0 => "1_1|2_3|4_6"
1 => "1_1|4_6|2_3"
2 => "2_3|1_1|4_6"
3 => "2_3|4_6|1_1"
4 => "4_6|1_1|2_3"
5 => "4_6|2_3|1_1"
]
一维数组所有的组合情况(排列组合)
$array = array('Alpha', 'Beta', 'Gamma', 'Sigma');
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1);
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
返回的结果
Array
(
[0] => Alpha
[1] => Alpha Beta
[2] => Alpha Beta Gamma
[3] => Alpha Beta Gamma Sigma
[4] => Alpha Beta Sigma
[5] => Alpha Beta Sigma Gamma
[6] => Alpha Gamma
[7] => Alpha Gamma Beta
[8] => Alpha Gamma Beta Sigma
[9] => Alpha Gamma Sigma
[10] => Alpha Gamma Sigma Beta
[11] => Alpha Sigma
[12] => Alpha Sigma Beta
[13] => Alpha Sigma Beta Gamma
[14] => Alpha Sigma Gamma
[15] => Alpha Sigma Gamma Beta
.
.
.
[59] => Sigma Gamma
[60] => Sigma Gamma Alpha
[61] => Sigma Gamma Alpha Beta
[62] => Sigma Gamma Beta
[63] => Sigma Gamma Beta Alpha
)