Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How can I find the index of the biggest element in an array?

by simmisam (Novice)
on Jan 15, 2014 at 21:50 UTC ( [id://1070730]=note: print w/replies, xml ) Need Help??


in reply to How can I find the index of the biggest element in an array?

my @array1 = qw(4 3 7 8 9 49 12 23 43); my $largest = (sort {$b <=> $a} @array1)[0]; my ($index) = grep {$array1[$_] ~~ $largest} 0..$#array1; print "Number = $largest, Index = $index\n";

Replies are listed 'Best First'.
Re: Answer: How can I find the index of the biggest element in an array?
by dcmertens (Scribe) on Jan 16, 2014 at 02:19 UTC
    I disagree. This is kinda clever, but I suspect that a single pass would be clearer. I would do this:
    my @array = qw(4 3 7 8 9 49 12 23 43); my ($largest, $largest_idx) = ($array1[0], 0); for my $i (1 .. $#array) { ($largest, $largest_idx) = ($array[$i], $i) if $largest < $array[$i]; } print "Largest number is $largest, at offset $largest_idx\n";
    It really seems like something like this should be available in List::Util or List::MoreUtils, and I would use one of those instead of the sort+smartmatch. At any rate, I am most likely to need this sort of calculation in PDL, where I would do it like this:
    use PDL; my $data = pdl(qw(4 3 7 8 9 49 12 23 43)); my $largest_idx = $data->maximum_ind; my $largest = $data->at($max_idx); print "Largest number is $largest, at offset $largest_idx\n";
    but PDL would be overkill for a dataset of this size.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1070730]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2025-06-17 19:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.