Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: How to get the index of smallest whole number in an array? (Simplified)

by BrowserUk (Patriarch)
on Jul 01, 2018 at 06:25 UTC ( [id://1217678]=note: print w/replies, xml ) Need Help??


in reply to How to get the index of smallest whole number in an array?

List::Util::reduce()

my @array = ('3','4','71','1', '-598', '-100203'); print reduce{ $a = $b if $array[$b] >=0 and $array[$b] < $array[$a]; $ +a } 0 .. $#array;; 3

Or more simply:

print reduce{ $array[$b] >=0 && $array[$b] < $array[$a] ? $b : $a } 0 +.. $#array;

Bad data -- ie. empty array, or all negatives -- returns undef. Doesn't check values are integer.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
In the absence of evidence, opinion is indistinguishable from prejudice. Suck that fhit

Replies are listed 'Best First'.
Re^2: How to get the index of smallest whole number in an array? (Simplified)
by Eily (Monsignor) on Jul 06, 2018 at 08:28 UTC

    all negatives -- returns undef
    No you get 0 with all negatives, since the first thing reduce does is set $a to the first value in the list. Though there is more than one way to solve this, I didn't find a one that doesn't involve re-checking $a on each iteration.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (1)
As of 2024-04-19 18:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found