Alignment and performance comparisons in PHP

Source: Internet
Author: User
Tags foreach

Permutation combination formula/permutation combination calculation formula P refers to the arrangement, from n elements to take R to arrange. Formula C refers to the combination, from n elements to take R, do not arrange, but in PHP we can use the N method to write, but each one of the performance will be different, let's take a look at it.

The requirement is this:

A combination of all possible specified lengths in the array is found, requiring no repetition.

Method One:

code 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 = Getcombinati Ontostring ($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);
$t = getcombinationtostring ($arr, 6);

Var_dump ($t);

Execution time: 238ms.

Method Two:

The code is as follows

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);

Execution time: 710ms.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.