我想写一个组合数学算法来获得 k的所有可能的组合
出 N
无重复。
I'm trying to write a combinatorics algorithm to get all the possible combinations of k
out of n
without repetitions.
其计算公式为:
n!/(k!(n-k)!));
结果最终在数组中。我实际上已经写的是这样的:
The results end up in an array. What I've actually written is this:
function Factorial($x)
{
if ($x < 1)
{
echo "Factorial() Error: Number too small!";
)
$ans = 1;
for ($xx = 2; $xx >= $x; $xx++)
{
$ans = $ans * $xx;
}
return($ans);
}
function Combination($selectcount,$availablecount)
{
$ans = Factorial($availablecount) / (
Factorial($availablecount - $selectcount) * Factorial($selectcount)
);
return ($ans);
}
这是实现此目的的最快方法是什么?有没有一种方法,以加快这?也许递归写呢?
Is this the fastest way to accomplish this? Is there a way to speed this up? Maybe to write it recursively?
这是我曾经得到了一个因子循环速度最快的:
This is the fastest I've ever managed to get a factorial loop:
function Factorial($factVal) {
if ($factVal < 0) {
die("Factorial() Error: Number too small!");
}
$factorial = 1;
while ($factVal > 1) {
$factorial *= $factVal--;
}
return $factorial ;
}