排列组合
数学上的阶乘、排列、组合的实现
代码实现
<?php
function factorial(int $n)
{
return array_product(range(1, $n));
}
function A(int $n, int $m)
{
return factorial($n) / factorial($n - $m);
}
function C($n, $m)
{
return A($n, $m) / factorial($m);
}
function arrangement($a, $m)
{
$r = [];
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i = 0; $i < $n; $i++) {
$b = $a;
$t = array_splice($b, $i, 1);
if ($m == 1) {
$r[] = $t;
} else {
$c = arrangement($b, $m - 1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
function combination(array $a, int $m)
{
$r = [];
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i = 0; $i < $n; $i++) {
$t = [$a[$i]];
if ($m == 1) {
$r[] = $t;
} else {
$b = array_slice($a, $i + 1);
$c = combination($b, $m - 1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
var_dump(C(5, 3));
var_dump(combination(range(1, 3), 2));
var_dump(arrangement(range(1, 3), 2));