Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: How to get the index of smallest whole number in an array?

by johngg (Canon)
on Jul 01, 2018 at 11:06 UTC ( [id://1217688]=note: print w/replies, xml ) Need Help??


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

The extra maps could be dispensed with I think.

johngg@abouriou ~/perl/Monks $ perl -Mstrict -Mwarnings -E ' my @arr = ( 3, 4, 71, 1, -598, -100203 ); say for ( sort { $arr[ $a ] <=> $arr[ $b ] } grep { $arr[ $_ ] >= 0 } 0 .. $#arr )[ 0 ];' 3

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^3: How to get the index of smallest whole number in an array?
by corenth (Monk) on Jul 02, 2018 at 18:07 UTC
    I love reading through answers to even "simple" questions because I get to see new ways to solve problems and new syntax. This code is a prime example. Embedding code in a for loop like this is something I've never even thought of, but it makes sense that you can do that.

    But, what's with the [ 0 ] at the end?

    my @arr = ( 3, 4, 71, 1, -598, -100203 ); say for ( sort { $arr[ $a ] <=> $arr[ $b ] } grep { $arr[ $_ ] >= 0 } 0 .. $#arr )[ 0 ]; # okay. what's with the [ 0 ] ??????

    I really want to know!

    
    
    
    $state{tired}?sleep(40):eat($food);
      ... what's with the [ 0 ] at the end?

      If you liked that, take another look at kcott's  ( ... )[0][0] approach. That said, it's still not an O(n) solution and therefore not, in general, and all things being equal, to be preferred IMHO.


      Give a man a fish:  <%-{-{-{-<

      Update:Corrected ordering. Thanks to AnomalousMonk

      The for is unnecessary. This is equivalent:say ( ... )[0].

      The contents of the parens creates an order list smallest to largest; the [0] selects the first element of that list.


      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
        Thanks for the explanation. I'll be playing with the new (for me) syntax :)
        
        
        
        $state{tired}?sleep(40):eat($food);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-25 08:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found