I'm trying to write a combinatorics algorithm to get all the possible combinations of k out of n without repetitions.
The formula is:
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?
ifblock. This is why it is always a good idea to properly space your code out.:)