Skip to content

Instantly share code, notes, and snippets.

@thesocialdev
Last active October 27, 2017 14:26
Show Gist options
  • Save thesocialdev/6a76f46591e4436730d52d03b6f89b8f to your computer and use it in GitHub Desktop.
Save thesocialdev/6a76f46591e4436730d52d03b6f89b8f to your computer and use it in GitHub Desktop.
N-Choose-K problem with recursion
<?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