On 10/26/09 Mon  Oct 26, 2009  8:45 AM, "Michael Alipio"
<daem0n...@yahoo.com> scribbled:

> Thanks for the advice. Forgive me if I sounded like someone who's frustrated,
> couldn't do his homework asking somebody else for help.
> 
> When I was learning C programming, I read that learning those difficult
> algorithms such as bubble sort, quick sort, binary search, is something that
> only programming students have to deal with.

Those are not difficult algorithms. They are algorithms that any programmer
should know. If you are learning how to program, then you are a "programming
student". However, generating a complete set of permutations efficiently for
any size set IS a difficult algorithm.

> I knew I needed a recursive function, I just didn't know how to start.
> What confused me more is that the code I found is a lot different from what I
> was initially thinking. He used the builtin function substr in the code in a
> way that I couldn't figure how it worked.

You don't "need" a recursive function. Using a recursive function can
sometimes be an elegant method for solving a difficult problem. However,
alternate solutions not using recursive functions can always be found.

> 
> See below:
> 
> my $result = '';
> 
> perm(0,2);
> 
> sub perm($$){
> my ($cur,$max) = @_;
> 
> if ($cur>=$max){
>  print "$result\n";
> return;
> }
> 
> for(@word){
> substr($result,$cur,1)=$_;
> perm($cur+1,$max);
> }
> }
> 
> What's the use of double ($$) after sub perm?? Does it have anything to do
> with process IDs (perldoc perlvar says so)?

The ($$) is a function prototype indicating that the function accepts two
scalars. See 'perldoc perlsub' and search for 'Prototypes'.

> 
> This line is also confusing:
> substr($result,$cur,1)= $_;
>  
> Substr returns a list, right? The first parameter is the expression, 2nd is
> the offset, and last is the length.
> The above line is too cryptic for me. What confused me more is that the return
> value of substr was assigned the $_.

No, substr returns a scalar. It can also return an lvalue if its first
argument is an lvalue, as is being done in this case. This allows you to
assign to a subset of a string scalar the value appearing to the right of
the equal sign ($_), thereby replacing part of the string. You can perform
the same function by including the replacement part as a fourth argument to
substr. See 'perldoc -f substr' for details.



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to