您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)使用PHP怎么實現(xiàn)笛卡爾積算法,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
具體如下:
<?php $arr = array(array(1,3,4,5),array(3,5,7,9),array(76,6,1,0)); /** ** 實現(xiàn)二維數(shù)組的笛卡爾積組合 ** $arr 要進行笛卡爾積的二維數(shù)組 ** $str 最終實現(xiàn)的笛卡爾積組合,可不寫 ** @return array **/ function cartesian($arr,$str = array()){ //去除第一個元素 $first = array_shift($arr); //判斷是否是第一次進行拼接 if(count($str) > 1) { foreach ($str as $k => $val) { foreach ($first as $key => $value) { //最終實現(xiàn)的格式 1,3,76 //可根據(jù)具體需求進行變更 $str2[] = $val.','.$value; } } }else{ foreach ($first as $key => $value) { //最終實現(xiàn)的格式 1,3,76 //可根據(jù)具體需求進行變更 $str2[] = $value; } } //遞歸進行拼接 if(count($arr) > 0){ $str2 = cartesian($arr,$str2); } //返回最終笛卡爾積 return $str2; } $cartesian_product = cartesian($arr); print_r($cartesian_product); ?>
最終輸出格式
Array
(
[0] => 1,3,76
[1] => 1,3,6
[2] => 1,3,1
[3] => 1,3,0
[4] => 1,5,76
[5] => 1,5,6
[6] => 1,5,1
[7] => 1,5,0
[8] => 1,7,76
[9] => 1,7,6
[10] => 1,7,1
[11] => 1,7,0
[12] => 1,9,76
[13] => 1,9,6
[14] => 1,9,1
[15] => 1,9,0
[16] => 3,3,76
[17] => 3,3,6
[18] => 3,3,1
[19] => 3,3,0
[20] => 3,5,76
[21] => 3,5,6
[22] => 3,5,1
[23] => 3,5,0
[24] => 3,7,76
[25] => 3,7,6
[26] => 3,7,1
[27] => 3,7,0
[28] => 3,9,76
[29] => 3,9,6
[30] => 3,9,1
[31] => 3,9,0
[32] => 4,3,76
[33] => 4,3,6
[34] => 4,3,1
[35] => 4,3,0
[36] => 4,5,76
[37] => 4,5,6
[38] => 4,5,1
[39] => 4,5,0
[40] => 4,7,76
[41] => 4,7,6
[42] => 4,7,1
[43] => 4,7,0
[44] => 4,9,76
[45] => 4,9,6
[46] => 4,9,1
[47] => 4,9,0
[48] => 5,3,76
[49] => 5,3,6
[50] => 5,3,1
[51] => 5,3,0
[52] => 5,5,76
[53] => 5,5,6
[54] => 5,5,1
[55] => 5,5,0
[56] => 5,7,76
[57] => 5,7,6
[58] => 5,7,1
[59] => 5,7,0
[60] => 5,9,76
[61] => 5,9,6
[62] => 5,9,1
[63] => 5,9,0
)
小編這里參考前面一篇《JavaScript笛卡爾積超簡單實現(xiàn)算法》,給出一個php計算笛卡爾積的超簡單算法示例如下:
<?php function cartesian($arr1,$arr2){ $relarr = array(); foreach($arr1 as $v1){ foreach($arr2 as $v2){ array_push($relarr,$v1.",".$v2); } } return $relarr; } //用法示例 $a = array('1','2','3'); $b = array('a','b',c); print_r(cartesian($a,$b)); ?>
運行結(jié)果:
Array
(
[0] => 1,a
[1] => 1,b
[2] => 1,c
[3] => 2,a
[4] => 2,b
[5] => 2,c
[6] => 3,a
[7] => 3,b
[8] => 3,c
)
以上就是使用PHP怎么實現(xiàn)笛卡爾積算法,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。