求一个数组,n个元素的不同组合(排列组合问题)
程序员文章站
2024-01-06 14:07:10
...
array('a1','b2','c3','d4','e5','x1','y1','z1');比如以上数组
我想要这个数组元素中三个元素的不同组合,例如下
array('a1','b2','c3');
array('a1','b2','d4');
array('a1','b2','e5');
array('a1','b2','x1');
array('a1','b2','y1');
方法一:最先想到的就是n次foreach循环,该方法简单粗暴
$data = array('a1','b2','c3','d4','e5','x1','y1','z1');
foreach ($data as $k_1 => $v_1) {
foreach ($data as $k_2 => $v_2) {
foreach ($data as $k_3 => $v_3) {
if ($v_1 !== $v_2 && $v_1 !== $v_3 && $v_2 !== $v_3) {
var_dump([$v_1,$v_2,$v_3]);
}
}
}
}
方法二:运用递归
<?php
$arr = array('a','b','c','d');
$result = array();
$t = getCombinationToString($arr, 3);
print_r($t);
function getCombinationToString($arr, $m) {
if ($m ==1) {
return $arr;
}
$result = array();
$tmpArr = $arr;
unset($tmpArr[0]);
for($i=0;$i<count($arr);$i++) {
$s = $arr[$i];
$ret = getCombinationToString(array_values($tmpArr), ($m-1));
foreach($ret as $row) {
$result[] = $s . $row;
}
}
return $result;
}
?>
结果如下:
Array
(
[0] => abc
[1] => abd
[2] => acc
[3] => acd
[4] => adc
[5] => add
[6] => bbc
[7] => bbd
[8] => bcc
[9] => bcd
[10] => bdc
[11] => bdd
[12] => cbc
[13] => cbd
[14] => ccc
[15] => ccd
[16] => cdc
[17] => cdd
[18] => dbc
[19] => dbd
[20] => dcc
[21] => dcd
[22] => ddc
[23] => ddd
)
文章出处:https://segmentfault.com/q/1010000005748820?_ea=890576