in reply to Why does my get_max_index function return zero? (High Water Mark Algorithm)
because you mask original $imax inside the loop with my $imax=$i...
Below is a more esoteric way to do it without a function. It goes under the "Schwartzian transform":
my @arr = (1,2,3,5,10,3,4,300,1,2,-2); my ($i) = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_ , $a +rr[$_] ] } 0..$#arr; print "i=$i\n"; # index 7 => value 300
starting from right to left, create an array of all the indices in your array, package the index and its value into a temporary arrayref and then into an intermediate array, sort that intermediate array with custom sort function which sorts in reverse (i.e. biggest first) wrt the second element in said packaged arrayref (which is the value). Remember index and value are still packaged together, so extract the index (first item of the arrayref) with the leftmost map which returns an array of indices of the items in your original array sorted by their value. However my ($i) = ... will retain only the first item (the index with largest value) and skip the rest.
sort of...
bw bliako
Edit: changed $#arr-1 to $#arr, thanks AnomalousMonk
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Why does my get_max_index function return zero? (High Water Mark Algorithm)
by AnomalousMonk (Archbishop) on Jun 03, 2019 at 21:41 UTC | |
by bliako (Abbot) on Jun 03, 2019 at 23:41 UTC | |
by AnomalousMonk (Archbishop) on Jun 04, 2019 at 02:36 UTC | |
by bliako (Abbot) on Jun 04, 2019 at 11:47 UTC |