首页 > 代码库 > 多数组求笛卡尔积
多数组求笛卡尔积
/*--------------------------------------
*+多数组求笛卡尔积
*--------------------------------------
*/
笛卡尔(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‘,‘a3‘), ‘b‘, array(‘c1‘,‘c2‘), array(‘d1‘,‘d2‘,‘d3‘), //......省略其它元素(也可以是数组),);$r = Descartes( $arr );var_dump($r);exit;/*array(18) { [0]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d1" } [1]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d2" } [2]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d3" } [3]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d1" } [4]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d2" } [5]=> array(4) { [0]=> string(2) "a1" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d3" } [6]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d1" } [7]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d2" } [8]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d3" } [9]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d1" } [10]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d2" } [11]=> array(4) { [0]=> string(2) "a2" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d3" } [12]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d1" } [13]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d2" } [14]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c1" [3]=> string(2) "d3" } [15]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d1" } [16]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d2" } [17]=> array(4) { [0]=> string(2) "a3" [1]=> string(1) "b" [2]=> string(2) "c2" [3]=> string(2) "d3" }}*/
多数组求笛卡尔积
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。