Update: Well, eating some crow...looks like I goofed on the problem requirements. The advice I give here is good, but it is for a different problem! Darn. I re-coding the variant that passes an array reference in a thread further down. It makes the most sense to use an index if the problem requires an index to be returned.
I will make a few other comments:sub get_max_index { #revisit how to define functions/"my" var ? (defa +ult parameters?) my $imax=0; for (my $i=0; $i<@_; $i++) { $imax=$_[$i] if ($imax<=$_[$i]);} return $imax; }
As a further possibility for your study is a version where a reference to @arr is passed to the subroutine. This is faster than the previous because only a single value is passed to the sub instead of all 10 elements. You will note that this version does one more comparison than absolutely necessary. That is due to the way that the loop is initialized. Tradeoffs where a slight performance hit results in much cleaner source code abound. Here is what that looks like:use strict; use warnings; sub get_max_index { my (@copyOfArray) = @_; #make an explicit local copy my $imax= shift @copyOfArray; # modifies this copy, but ok for (@copyOfArray){ # no indices... $imax = $_ if $imax < $_; } return $imax; } my @arr = (1..10); my $ans = get_max_index(@arr); print"$ans\n";
Now of course the "right" way to implement this function is not to implement it at all and use the version in List::Util as pointed out by karlgoethebier. I see some Monks offered sorting solutions. Yes that works but is way less efficient than linearly scanning for the max and/or min (can do both at the same time).use strict; use warnings; sub get_max_index { my $arrayRef = shift; my $imax = $arrayRef->[0]; #don't modify @arr for (@$arrayRef){ $imax = $_ if $imax < $_; } return $imax; } my @arr = (1..10); my $ans = get_max_index(\@arr); #pass reference to array! print"$ans\n";
I hope that my examples are understandable to you that they help you upon your Perl journey. Even a very small section of code can have a lot of Perl "fine points". Wish you well!
In reply to Re: Why does my get_max_index function return zero? (High Water Mark Algorithm)
by Marshall
in thread Why does my get_max_index function return zero? (High Water Mark Algorithm)
by hghosh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |