PHP排列组合

多个元素的排列组合

  解决问题:求一个含有N个元素的数组中取出M个元素组成新的数组,一共可以组合成的数组并输出。

<?php  
function getCombinAryByNum( $a, $n,$t=array()) {  
  if ($n == 0) {
    return array($t);
  }
  $r = array();
  for ($i=0,$l=count($a); $i <= $l-$n; $i++) {
    $tmp = getCombinAryByNum( array_slice($a, $i+1, $l, false), $n-1,array_merge($t, array($a[$i])));
    $r = array_merge($r, $tmp);
  }
  return $r;
}

$ss = getCombinAryByNum(array(1,2,3,4,5,6,7,8,9,0),2);
print_r($ss);  
二维数组的排列组合
<?php  
$CombinList = array(
            1 => array(0,1,2),
            2 => array(1,2,3,4),
            3 => array(2,3,4),
            4 => array(0,1,2,3)
        );
/* 计算C(a,1) * C(b, 1) * ... * C(n, 1)的值 */
$CombineCount = 1;
foreach($CombinList as $Key => $val)  
{
    $CombineCount *= count($val);
}
$r = $CombineCount;
foreach($CombinList as $k => $v)  
{
    // $v中的元素在拆分成组合后纵向出现的最大重复次数
    $r = $r / count($v);
    $StartPosition = 1;
    // 开始对每个进行循环
    foreach($v as $s)
    {
        $TempStartPosition = $StartPosition;
        $SpaceCount = $CombineCount / count($v) / $r;
        for($J = 1; $J <= $SpaceCount; $J ++)
        {
            for($I = 0; $I < $r; $I ++)
            {
               $res[$TempStartPosition + $I][$k] = $s;
            }
            $TempStartPosition += $r * count($v);
        }
        $StartPosition += $r;
    }
}

print_r($res);