求笛卡尔积的php代码

笛卡尔(Descartes)乘积又叫直积。设A、B是任意两个集合,在集合A中任意取一个元素x,在集合B中任意取一个元素y,组成一个有序对(x,y),把这样的有序对作为新的元素,他们的全体组成的集合称为集合A和集合B的直积,记为A×B,即A×B={(x,y)|x∈A且y∈B}。

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),
  //......省略其它元素(也可以是数组),
);
 
$r = Descartes( $arr );

结果

Array
(
    [0] => Array
        (
            [0] => a1
            [1] => b
            [2] => c1
            [3] => d1
        )

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

    [2] => Array
        (
            [0] => a1
            [1] => b
            [2] => c1
            [3] => d3
        )

    [3] => Array
        (
            [0] => a1
            [1] => b
            [2] => c2
            [3] => d1
        )

    [4] => Array
        (
            [0] => a1
            [1] => b
            [2] => c2
            [3] => d2
        )

    [5] => Array
        (
            [0] => a1
            [1] => b
            [2] => c2
            [3] => d3
        )

    [6] => Array
        (
            [0] => a2
            [1] => b
            [2] => c1
            [3] => d1
        )

    [7] => Array
        (
            [0] => a2
            [1] => b
            [2] => c1
            [3] => d2
        )

    [8] => Array
        (
            [0] => a2
            [1] => b
            [2] => c1
            [3] => d3
        )

    [9] => Array
        (
            [0] => a2
            [1] => b
            [2] => c2
            [3] => d1
        )

    [10] => Array
        (
            [0] => a2
            [1] => b
            [2] => c2
            [3] => d2
        )

    [11] => Array
        (
            [0] => a2
            [1] => b
            [2] => c2
            [3] => d3
        )

)


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值