Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by Skeeve (Parson)
on May 27, 2007 at 18:57 UTC ( [id://617760]=note: print w/replies, xml ) Need Help??


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

my $i = $#data; my $max = $i; $max = $data[$i] > $data[$max] ? $i : $max while $i--; print "Max value is $data[$max], at index $max\n"

Replies are listed 'Best First'.
Re: Answer: How can I find the index of the biggest element in an array?
by Jenda (Abbot) on May 28, 2007 at 14:09 UTC

    I don't think it's good to scare people with a ternary operator and statement modifier in one statement. I do think

    while ($i--) { $max = $i if $data[$i] > $data[$max]; }
    would be much more readable. I'd probably write it like this though:
    my $max = 0; for (0 .. $#data) { $max = $_ if $data[$_] > $data[$max] }

    Update (suggested by ysth): It's actually better to start looping at index 1:

    my $max = 0; for (1 .. $#data) { $max = $_ if $data[$_] > $data[$max] }
    There's no point in comparing the first element to itself.

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2025-06-17 11: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.