Last active
October 27, 2017 14:26
-
-
Save thesocialdev/6a76f46591e4436730d52d03b6f89b8f to your computer and use it in GitHub Desktop.
N-Choose-K problem with recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
N-Choose-K problem solved with recursion | |
I decided to write this code after seeing this video https://www.youtube.com/watch?v=Hmld7MhFUDk | |
It can be easily executed at http://phpfiddle.org/ | |
*/ | |
function nChooseK ($n, $k, &$count, $_performanceFlag){ | |
$count++; | |
if ($k>$n-1 || $k < 1) // if K is larger than N the function returns 0 because n,k: 1 <= k <= n-1 (See Wolframalpha or Google it, for example, https://en.wikipedia.org/wiki/Binomial_coefficient#Computing_the_value_of_binomial_coefficients) | |
return 0; | |
if (($k == 0) || ($n == $k)) // criteria based on the pascal triangle | |
return 1; | |
else if (($k == 1 || $n-1 == $k) && $_performanceFlag) // increases performance based on pascal triangle patterns | |
return $n; | |
else | |
return nChooseK($n-1, $k-1, $count,$_performanceFlag) + nChooseK($n-1,$k,$count,$_performanceFlag); | |
} | |
/* | |
Examples for C(20,5) and count of iteration to analize performance | |
It can be compared with Wolfram Alpha at https://www.wolframalpha.com/input/?i=C(20,5) | |
*/ | |
$count = 0; | |
echo "n-choose-k good performance: ".nChooseK(20,5, $count, true); | |
echo "<br>"."Iteration: ".$count; | |
$count = 0; | |
echo "<br>"."<br>"."n-choose-k bad performance: ".nChooseK(20,5, $count, false); | |
echo "<br>"."Iteration: ".$count; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment