日期:2014-05-17  浏览次数:20466 次

经典的笛卡尔乘积代码,要怎么修改它?
笛卡尔乘积代码:

<?PHP

function Descartes() {  
  $t = func_get_args();  
  if(func_num_args() == 1) return call_user_func_array( __FUNCTION__, $t[0] );  
  $a = array_shift($t);  
  if(! is_array($a)) $a = array($a);  
  $a = array_chunk($a, 1);  
  do {  
  $r = array();  
  $b = array_shift($t);  
  if(! is_array($b)) $b = array($b);  
  foreach($a as $p)  
  foreach(array_chunk($b, 1) as $q)  
  $r[] = array_merge($p, $q);  
  $a = $r;  
  }while($t);  
  return $r;  
}  

$arr = array(  
  array('a1','a2'),  
  'b',  
  array('c1','c2'),  
  array('d1','d2','d3'),
  array('e1','e2','e3')
  //......省略其它元素(也可以是数组),  
);  
   
$r = Descartes( $arr );  
print_r($r);
?>

//////////////////////////////////////

输出:

Array
(
  [0] => Array
  (
  [0] => a1
  [1] => b
  [2] => c1
  [3] => d1
  [4] => e1
  )
  [1] => Array
  (
  [0] => a1
  [1] => b
  [2] => c1
  [3] => d1
  [4] => e2
  )
  ...。。。



////////////////////
现在我只想要3个元素,第一个元素要有a1或a2。那段代码要怎么改?
Array
(
  [0] => Array
  (
  [0] => a1
  [1] => b
  [2] => c1
  )
  ......
  [1] => Array
  (
  [0] => a2
  [1] => c2
  [2] => d3
  )
  ......




------解决方案--------------------
对于
$arr = array(
array('a1','a2'),
'b',
array('c1','c2'),
array('d1','d2','d3'),
array('e1','e2','e3')
//......省略其它元素(也可以是数组),
);
需先对
$arr = array(
'b',
array('c1','c2'),
array('d1','d2','d3'),
array('e1','e2','e3')
//......省略其它元素(也可以是数组),
);
求 M 取 2 的组合
$c = combination($arr, 2);
然后对组合的结果求笛卡尔积

$r = array();
foreach($c as $v)
$r = array_merge($r, Descartes( array('a1','a2'), $v[0], $v[1] )); 
print_r($r);
PHP code
Array
(
    [0] => Array
        (
            [0] => a1
            [1] => d1
            [2] => e1
        )

    [1] => Array
        (
            [0] => a1
            [1] => d1
            [2] => e2
        )

    [2] => Array
        (
            [0] => a1
            [1] => d1
            [2] => e3
        )

    [3] => Array
        (
            [0] => a1
            [1] => d2
            [2] => e1
        )

    [4] => Array
        (
            [0] => a1
            [1] => d2
            [2] => e2
        )

    [5] => Array
        (
            [0] => a1
            [1] => d2
            [2] => e3
        )

    [6] => Array
        (
            [0] => a1
            [1] => d3
            [2] => e1
        )

    [7] => Array
        (
            [0] => a1
            [1] => d3
            [2] => e2
        )

    [8] => Array
        (
            [0] => a1