PHP Full permutation algorithm Implementation program code
Any element of M (m≤n) from n different elements, arranged in a certain order, is called an arrangement of extracting m elements from n different elements. All permutations are called when m=n.
Brief introduction
The full arrangement of three elements such as the three-in-one is:
The
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
Total 3*2*1=6 species 3!
2 formula
Number of full permutations f (n) =n! (Definition 0!=1)
Recursive algorithm
The
1,3,2
2,1,3
2,3,1
3,2,1
3,1,2
This is because the algorithm only takes into account how the output is fully aligned, regardless of whether there is a problem with the transposition. So I proposed the solution, that is, the transposition function modified under
such as 1 2 3 transposition, should not be directly 3 2 1 so that 3 and 1 direct transposition; Instead, let the 3 rank at the front and back, 1 2 backwards.
Basic algorithms
The following is a description of the total permutation algorithm four:
(A) Dictionary ordering method
(B) Increment of rounding method
(C) Descending rounding Method
(D) adjacent position swap method
Implementing a full permutation algorithm
| The code is as follows |
|
|
Header ("Content-type:text/html;charset=utf-8");/**
* @param array $a the set of elements to be arranged, will change dynamically
* @param array $b storage current arrangement
* @param array $M The set of elements to be arranged, equivalent to a constant, always the initial set of elements to be arranged
*/
function Wholerange ($a, $b, $M) {
$range =array ();
if (count ($a) > 1) {
$d = $b;
foreach ($a as $value) {
$b []= $value;
$c =array_diff ($M, $b);
if (count ($c) > 0) {
$range []=wholerange ($c, $b, $M);
}
$b = $d;
}
}elseif (count ($a) = = 1) {
foreach ($a as $value) {
$b []= $value;
}
$onerange = "";
foreach ($b as $value) {
$onerange. = $value;
}
$range []= $onerange;
}
return $range;
}
/**
* Recursive output array
*
* @param array $arr to be output
* @return Int returns the number of array elements */
function Recursionarray ($arr) {
$i = 0;
foreach ($arr as $value) {
if (Is_array ($value)) {
$i +=recursionarray ($value);
}else{
echo $value. "
";
$i + +;
}
}
return $i;
}
$a =array (' A ', ' B ', ' C ', ' D ');
$b =array ();
$range =wholerange ($a, $b, $a);
$count =recursionarray ($range);
echo "A total of". $count. " Arrangement ";
?> |
http://www.bkjia.com/PHPjc/941716.html www.bkjia.com true http://www.bkjia.com/PHPjc/941716.html techarticle The PHP full permutation algorithm implements code that takes M (MN) elements from n different elements, arranged in a certain order, and is called an arrangement of extracting m elements from n different elements. When ...