|
Posted by Craig Storey on 07/26/06 16:18
all_my_trash@hotmail.com wrote:
> Hello!
>
> I'm trying to write an algorithm which can fill an array with all the
> possible combinations of r out of n, without repetition (maximum
> combinations = n!/(r!(n-r)!))
>
> However, my mathematical skills are insufficient - does anybody have
> such an algorithm for sharing?
>
> Regards,
> OMykle
>
Hopefully this isn't for homework...but if it is then you are copying
mine. :) This is untested code, but mathematically correct. For bonus
marks you can figure out how to do this recursively.
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 Permutation($selectcount,$availablecount)
{
$ans = Factorial($availablecount) /
Factorial($availablecount-$selectcount);
return ($ans);
}
function Combination($selectcount,$availablecount)
{
$ans = Factorial($availablecount) / (
Factorial($availablecount-$selectcount) * Factorial($selectcount) );
return ($ans);
}
Navigation:
[Reply to this message]
|