Home  >  Article  >  Backend Development  >  Permutation, combination and performance comparison in PHP_PHP tutorial

Permutation, combination and performance comparison in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:04934browse

Permutation, combination and performance comparison in PHP

  Permutation and combination formula/Permutation and combination calculation formula Formula P refers to permutation, taking R elements from N elements to arrange them. Formula C refers to combination. R elements are taken from N elements without arrangement. But in PHP we can write it in N ways, but the performance of each writing method will be different. Let’s take a look below. .

The requirements are as follows:

Find all possible combinations of the specified length in the array without duplication.

Method 1:

The code is as follows

function getCombinationToString($arr,$m){
$result = array();
if ($m ==1){
return $arr;
}

if ($m == count($arr)){
$result[] = implode(',' , $arr);
return $result;
}

$temp_firstelement = $arr[0];
unset($arr[0]);
$arr = array_values($arr);
$temp_list1 = getCombinationToString($arr, ($m-1));

foreach ($temp_list1 as $s){
$s = $temp_firstelement.','.$s;
$result[] = $s;
}
unset($temp_list1);

$temp_list2 = getCombinationToString($arr, $m);
foreach ($temp_list2 as $s){
$result[] = $s;
}
unset($temp_list2);

return $result;
}
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
$t = getCombinationToString($arr, 6);

var_dump($t);

  执行时间:238ms。

  方法二:

代码如下  

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

代码如下  

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

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
$numum = 6;
$ss = getCombinAryByNum($arr,$numum);

var_dump($ss);

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
$numum = 6;
$ss = getCombinAryByNum($arr,$numum);

var_dump($ss);

  执行时间:710ms。

http://www.bkjia.com/PHPjc/918724.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/918724.htmlTechArticle
PHP中排列组合及性能对比 排列组合公式/排列组合计算公式公式P是指排列,从N个元素取R个进行排列。 公式C是指组合,从N个元素取R个,不进行...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn