in reply to Recursion problem
You need a name for the routine, say sumTo. And the args: the target and the list. So, you can write the skeleton:
sub sumTo { my $target = shift; ... }
sub sumTo { my $target = shift; my @list = @_; if( $list[ 0 ] ) == $target ) return 1; } return 0; }
sub sumTo { my $target = shift; for( @_ ) { if( $_ ) == $target ) return 1; } } return 0; }
If the target is in the list, it returns 1, otherwise it returns 0. And if the list is empty, it also returns 0;
In order to pick out the individual values from the list, we need to use indexes rather than the values directly. We can then slice @_ to reduce the list:
sub sumTo { my $target = shift; for( 0 .. $#_ ) { if( $_[ $_ ] == $target ) return 1; } else { if( sumTo( $target - $_[$_], @_[0 .. $_-1, $_+1 .. $#_] ) +) { return 1; } } } return 0; }
And that's it. The essence of recursion is to reduce the problem at each step to a similar, but simpler problem that will eventually converge. In this case, we pick out each number in the list and subtract it from the target. We then have a smaller target and a smaller list and we recurse to solve that problem. Eventually, the list will be reduced to 1 element, and if it matches the remaining target, we've solved the problem.
One element of the above to pay special consideration to is the slice operation which removes the current element from the list we recurse on:
@_[0 .. $_-1, $_+1 .. $#_]
Understanding how that works is left as an exercise, but be sure to understand it well--write a few small programs that display the results of that expression as the index iterates--because you can guarentee if this is homework, you are going to be questioned hard about that.
There is also an error in the above, so you're gonna have to understand it to some level before you will have a working program.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Recursion problem
by moritz (Cardinal) on May 25, 2008 at 09:46 UTC | |
by psini (Deacon) on May 25, 2008 at 09:55 UTC | |
by BrowserUk (Patriarch) on May 25, 2008 at 10:27 UTC | |
by moritz (Cardinal) on May 25, 2008 at 10:40 UTC | |
by BrowserUk (Patriarch) on May 25, 2008 at 11:22 UTC | |
by moritz (Cardinal) on May 25, 2008 at 11:41 UTC | |
|