Writing recursion is 2 tricks together. The first is to take a problem and break it into one or more simpler problems. The other is to figure out the simple problems that you will come to and make them special cases.
So in this case what do we want? We want a function that takes a number (m) and an array of n things, and returns all of the possible choices of m things from the list. Well we can make this simpler by deciding whether or not to choose the first element. That will reduce n, and possibly m as well, which has to be simpler.
Now what simple problems can we come down to? Well we could get down to needing no elements. In which case there is one list of no elements. Or we could get down to a situation where our list is shorter than the number we want, in which case we have no answers.
So we wind up with this:
Now a warning on recursion. Recursive problems where you make a *pair* of recursive calls (like this one) open you up to processing an exponential amount of data, or even returning that. (Certainly the case here!) This should be a danger flag, and when you reach for this you should either be willing to pay a very steep price, or you should know why in your situation it won't be a problem.# Takes a number and a list of elements. Returns all possible ways to # select that number out of the list. sub choose_m { my $m = shift; # Special cases first if (0 == $m) { return []; } elsif (@_ < $m) { return (); } else { # This is our recursion step my $first = shift; return ( # Things without the first element choose_m($m, @_), # Things with the first element map {[$first, @$_]} choose_m($m - 1, @_) ); } }
Try to write an iterative and a recursive solution to calculating Fibonacci numbers, see which is faster. Likewise Perl's RE engine uses recursion, if you look around you will find some discussions of the possible problems that result. And in this case, well try to list 30 choose 15 things, see what happens to your memory... :-)
In reply to Re (tilly) 1: nCr arrays of size r
by tilly
in thread nCr arrays of size r
by PsychoSpunk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |