in reply to Re: Why does my get_max_index function return zero? (High Water Mark Algorithm)
in thread Why does my get_max_index function return zero? (High Water Mark Algorithm)

Your code returns 10. It should return 9.


holli

You can lead your users to water, but alas, you cannot drown them.
  • Comment on Re^2: Why does my get_max_index function return zero? (High Water Mark Algorithm)
  • Download Code

Replies are listed 'Best First'.
Re^3: Why does my get_max_index function return zero? (High Water Mark Algorithm)
by Marshall (Canon) on Jun 04, 2019 at 17:57 UTC
    What?? it is supposed to return the next to the highest? Oh... My gosh.......this thing wants the index of highest value, not the highest value itself!! Should have read more carefully.. That of course changes things Ooops...Do not write code before consuming at least one full cup of coffee!

    Update:
    Ok, if the problem statement requires returning an index, then the most natural formulation would be to use indices. Here is how that looks when a reference to the array is passed to the sub. I just completely blew it and missed that key piece of info, probably because working with an index is a very rare in my coding. More usual in my problem space might be to return a reference to an entire row of a multidimensional array that matches some criteria. additional comment: I remember needing indices when working with some kinds of tk widgets. So a requirement for this sort of thing definitely exists.

    use strict; use warnings; sub get_max_index { my $arrayRef = shift; my $imax = 0; for my $i (0..@$arrayRef-1){ $imax = $i if $arrayRef->[$i] > $arrayRef->[$imax]; } return $imax; } my @arr = (1..10); my $ans = get_max_index(\@arr); #pass reference to array! print"$ans\n";
      Good, now try again using foreach, but without adding a loop counter =) In the meantime I will put on my flip-flops and chill at the lake.


      holli

      You can lead your users to water, but alas, you cannot drown them.
        Ok, I don't see an obvious way using the flip-flop operator....Please enlighten us...

        This idea using reduce which essentially has the equivalent of a foreach index did occur to me:

        use strict; use warnings; use List::Util qw(reduce); my @arr = qw(0 3 5 12 3 2 1);; my $maxi = reduce { $arr[$a] > $arr[$b] ? $a : $b } (0..@arr-1); print "maximum i = $maxi value=$arr[$maxi]\n"; # maximum i = 3 value=12
        Oh, and yes I almost always use @array-1 instead of $#array because I tend to either forget the right characters or type it somehow wrong.